Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67
  68    Example:
  69        >>> class Foo(Expression):
  70        ...     arg_types = {"this": True, "expression": False}
  71
  72        The above definition informs us that Foo is an Expression that requires an argument called
  73        "this" and may also optionally receive an argument called "expression".
  74
  75    Args:
  76        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  77        parent: a reference to the parent expression (or None, in case of root expressions).
  78        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  79            uses to refer to it.
  80        comments: a list of comments that are associated with a given expression. This is used in
  81            order to preserve comments when transpiling SQL code.
  82        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  83            optimizer, in order to enable some transformations that require type information.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def append(self, arg_key, value):
 262        """
 263        Appends value to arg_key if it's a list or sets it as a new list.
 264
 265        Args:
 266            arg_key (str): name of the list expression arg
 267            value (Any): value to append to the list
 268        """
 269        if not isinstance(self.args.get(arg_key), list):
 270            self.args[arg_key] = []
 271        self.args[arg_key].append(value)
 272        self._set_parent(arg_key, value)
 273
 274    def set(self, arg_key, value):
 275        """
 276        Sets `arg_key` to `value`.
 277
 278        Args:
 279            arg_key (str): name of the expression arg.
 280            value: value to set the arg to.
 281        """
 282        self.args[arg_key] = value
 283        self._set_parent(arg_key, value)
 284
 285    def _set_parent(self, arg_key, value):
 286        if hasattr(value, "parent"):
 287            value.parent = self
 288            value.arg_key = arg_key
 289        elif type(value) is list:
 290            for v in value:
 291                if hasattr(v, "parent"):
 292                    v.parent = self
 293                    v.arg_key = arg_key
 294
 295    @property
 296    def depth(self):
 297        """
 298        Returns the depth of this tree.
 299        """
 300        if self.parent:
 301            return self.parent.depth + 1
 302        return 0
 303
 304    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 305        """Yields the key and expression for all arguments, exploding list args."""
 306        for k, vs in self.args.items():
 307            if type(vs) is list:
 308                for v in vs:
 309                    if hasattr(v, "parent"):
 310                        yield k, v
 311            else:
 312                if hasattr(vs, "parent"):
 313                    yield k, vs
 314
 315    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 316        """
 317        Returns the first node in this tree which matches at least one of
 318        the specified types.
 319
 320        Args:
 321            expression_types: the expression type(s) to match.
 322
 323        Returns:
 324            The node which matches the criteria or None if no such node was found.
 325        """
 326        return next(self.find_all(*expression_types, bfs=bfs), None)
 327
 328    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 329        """
 330        Returns a generator object which visits all nodes in this tree and only
 331        yields those that match at least one of the specified expression types.
 332
 333        Args:
 334            expression_types: the expression type(s) to match.
 335
 336        Returns:
 337            The generator object.
 338        """
 339        for expression, *_ in self.walk(bfs=bfs):
 340            if isinstance(expression, expression_types):
 341                yield expression
 342
 343    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 344        """
 345        Returns a nearest parent matching expression_types.
 346
 347        Args:
 348            expression_types: the expression type(s) to match.
 349
 350        Returns:
 351            The parent node.
 352        """
 353        ancestor = self.parent
 354        while ancestor and not isinstance(ancestor, expression_types):
 355            ancestor = ancestor.parent
 356        return t.cast(E, ancestor)
 357
 358    @property
 359    def parent_select(self):
 360        """
 361        Returns the parent select statement.
 362        """
 363        return self.find_ancestor(Select)
 364
 365    @property
 366    def same_parent(self):
 367        """Returns if the parent is the same class as itself."""
 368        return type(self.parent) is self.__class__
 369
 370    def root(self) -> Expression:
 371        """
 372        Returns the root expression of this tree.
 373        """
 374        expression = self
 375        while expression.parent:
 376            expression = expression.parent
 377        return expression
 378
 379    def walk(self, bfs=True, prune=None):
 380        """
 381        Returns a generator object which visits all nodes in this tree.
 382
 383        Args:
 384            bfs (bool): if set to True the BFS traversal order will be applied,
 385                otherwise the DFS traversal will be used instead.
 386            prune ((node, parent, arg_key) -> bool): callable that returns True if
 387                the generator should stop traversing this branch of the tree.
 388
 389        Returns:
 390            the generator object.
 391        """
 392        if bfs:
 393            yield from self.bfs(prune=prune)
 394        else:
 395            yield from self.dfs(prune=prune)
 396
 397    def dfs(self, parent=None, key=None, prune=None):
 398        """
 399        Returns a generator object which visits all nodes in this tree in
 400        the DFS (Depth-first) order.
 401
 402        Returns:
 403            The generator object.
 404        """
 405        parent = parent or self.parent
 406        yield self, parent, key
 407        if prune and prune(self, parent, key):
 408            return
 409
 410        for k, v in self.iter_expressions():
 411            yield from v.dfs(self, k, prune)
 412
 413    def bfs(self, prune=None):
 414        """
 415        Returns a generator object which visits all nodes in this tree in
 416        the BFS (Breadth-first) order.
 417
 418        Returns:
 419            The generator object.
 420        """
 421        queue = deque([(self, self.parent, None)])
 422
 423        while queue:
 424            item, parent, key = queue.popleft()
 425
 426            yield item, parent, key
 427            if prune and prune(item, parent, key):
 428                continue
 429
 430            for k, v in item.iter_expressions():
 431                queue.append((v, item, k))
 432
 433    def unnest(self):
 434        """
 435        Returns the first non parenthesis child or self.
 436        """
 437        expression = self
 438        while type(expression) is Paren:
 439            expression = expression.this
 440        return expression
 441
 442    def unalias(self):
 443        """
 444        Returns the inner expression if this is an Alias.
 445        """
 446        if isinstance(self, Alias):
 447            return self.this
 448        return self
 449
 450    def unnest_operands(self):
 451        """
 452        Returns unnested operands as a tuple.
 453        """
 454        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 455
 456    def flatten(self, unnest=True):
 457        """
 458        Returns a generator which yields child nodes who's parents are the same class.
 459
 460        A AND B AND C -> [A, B, C]
 461        """
 462        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 463            if not type(node) is self.__class__:
 464                yield node.unnest() if unnest else node
 465
 466    def __str__(self):
 467        return self.sql()
 468
 469    def __repr__(self):
 470        return self._to_s()
 471
 472    def sql(self, dialect: DialectType = None, **opts) -> str:
 473        """
 474        Returns SQL string representation of this tree.
 475
 476        Args:
 477            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 478            opts: other `sqlglot.generator.Generator` options.
 479
 480        Returns:
 481            The SQL string.
 482        """
 483        from sqlglot.dialects import Dialect
 484
 485        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 486
 487    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 488        indent = "" if not level else "\n"
 489        indent += "".join(["  "] * level)
 490        left = f"({self.key.upper()} "
 491
 492        args: t.Dict[str, t.Any] = {
 493            k: ", ".join(
 494                v._to_s(hide_missing=hide_missing, level=level + 1)
 495                if hasattr(v, "_to_s")
 496                else str(v)
 497                for v in ensure_list(vs)
 498                if v is not None
 499            )
 500            for k, vs in self.args.items()
 501        }
 502        args["comments"] = self.comments
 503        args["type"] = self.type
 504        args = {k: v for k, v in args.items() if v or not hide_missing}
 505
 506        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 507        right += ")"
 508
 509        return indent + left + right
 510
 511    def transform(self, fun, *args, copy=True, **kwargs):
 512        """
 513        Recursively visits all tree nodes (excluding already transformed ones)
 514        and applies the given transformation function to each node.
 515
 516        Args:
 517            fun (function): a function which takes a node as an argument and returns a
 518                new transformed node or the same node without modifications. If the function
 519                returns None, then the corresponding node will be removed from the syntax tree.
 520            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 521                modified in place.
 522
 523        Returns:
 524            The transformed tree.
 525        """
 526        node = self.copy() if copy else self
 527        new_node = fun(node, *args, **kwargs)
 528
 529        if new_node is None or not isinstance(new_node, Expression):
 530            return new_node
 531        if new_node is not node:
 532            new_node.parent = node.parent
 533            return new_node
 534
 535        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 536        return new_node
 537
 538    def replace(self, expression):
 539        """
 540        Swap out this expression with a new expression.
 541
 542        For example::
 543
 544            >>> tree = Select().select("x").from_("tbl")
 545            >>> tree.find(Column).replace(Column(this="y"))
 546            (COLUMN this: y)
 547            >>> tree.sql()
 548            'SELECT y FROM tbl'
 549
 550        Args:
 551            expression (Expression|None): new node
 552
 553        Returns:
 554            The new expression or expressions.
 555        """
 556        if not self.parent:
 557            return expression
 558
 559        parent = self.parent
 560        self.parent = None
 561
 562        replace_children(parent, lambda child: expression if child is self else child)
 563        return expression
 564
 565    def pop(self):
 566        """
 567        Remove this expression from its AST.
 568
 569        Returns:
 570            The popped expression.
 571        """
 572        self.replace(None)
 573        return self
 574
 575    def assert_is(self, type_):
 576        """
 577        Assert that this `Expression` is an instance of `type_`.
 578
 579        If it is NOT an instance of `type_`, this raises an assertion error.
 580        Otherwise, this returns this expression.
 581
 582        Examples:
 583            This is useful for type security in chained expressions:
 584
 585            >>> import sqlglot
 586            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 587            'SELECT x, z FROM y'
 588        """
 589        assert isinstance(self, type_)
 590        return self
 591
 592    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 593        """
 594        Checks if this expression is valid (e.g. all mandatory args are set).
 595
 596        Args:
 597            args: a sequence of values that were used to instantiate a Func expression. This is used
 598                to check that the provided arguments don't exceed the function argument limit.
 599
 600        Returns:
 601            A list of error messages for all possible errors that were found.
 602        """
 603        errors: t.List[str] = []
 604
 605        for k in self.args:
 606            if k not in self.arg_types:
 607                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 608        for k, mandatory in self.arg_types.items():
 609            v = self.args.get(k)
 610            if mandatory and (v is None or (isinstance(v, list) and not v)):
 611                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 612
 613        if (
 614            args
 615            and isinstance(self, Func)
 616            and len(args) > len(self.arg_types)
 617            and not self.is_var_len_args
 618        ):
 619            errors.append(
 620                f"The number of provided arguments ({len(args)}) is greater than "
 621                f"the maximum number of supported arguments ({len(self.arg_types)})"
 622            )
 623
 624        return errors
 625
 626    def dump(self):
 627        """
 628        Dump this Expression to a JSON-serializable dict.
 629        """
 630        from sqlglot.serde import dump
 631
 632        return dump(self)
 633
 634    @classmethod
 635    def load(cls, obj):
 636        """
 637        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 638        """
 639        from sqlglot.serde import load
 640
 641        return load(obj)
 642
 643
 644IntoType = t.Union[
 645    str,
 646    t.Type[Expression],
 647    t.Collection[t.Union[str, t.Type[Expression]]],
 648]
 649ExpOrStr = t.Union[str, Expression]
 650
 651
 652class Condition(Expression):
 653    def and_(self, *expressions, dialect=None, **opts):
 654        """
 655        AND this condition with one or multiple expressions.
 656
 657        Example:
 658            >>> condition("x=1").and_("y=1").sql()
 659            'x = 1 AND y = 1'
 660
 661        Args:
 662            *expressions (str | Expression): the SQL code strings to parse.
 663                If an `Expression` instance is passed, it will be used as-is.
 664            dialect (str): the dialect used to parse the input expression.
 665            opts (kwargs): other options to use to parse the input expressions.
 666
 667        Returns:
 668            And: the new condition.
 669        """
 670        return and_(self, *expressions, dialect=dialect, **opts)
 671
 672    def or_(self, *expressions, dialect=None, **opts):
 673        """
 674        OR this condition with one or multiple expressions.
 675
 676        Example:
 677            >>> condition("x=1").or_("y=1").sql()
 678            'x = 1 OR y = 1'
 679
 680        Args:
 681            *expressions (str | Expression): the SQL code strings to parse.
 682                If an `Expression` instance is passed, it will be used as-is.
 683            dialect (str): the dialect used to parse the input expression.
 684            opts (kwargs): other options to use to parse the input expressions.
 685
 686        Returns:
 687            Or: the new condition.
 688        """
 689        return or_(self, *expressions, dialect=dialect, **opts)
 690
 691    def not_(self):
 692        """
 693        Wrap this condition with NOT.
 694
 695        Example:
 696            >>> condition("x=1").not_().sql()
 697            'NOT x = 1'
 698
 699        Returns:
 700            Not: the new condition.
 701        """
 702        return not_(self)
 703
 704
 705class Predicate(Condition):
 706    """Relationships like x = y, x > 1, x >= y."""
 707
 708
 709class DerivedTable(Expression):
 710    @property
 711    def alias_column_names(self):
 712        table_alias = self.args.get("alias")
 713        if not table_alias:
 714            return []
 715        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 716        return [c.name for c in column_list]
 717
 718    @property
 719    def selects(self):
 720        alias = self.args.get("alias")
 721
 722        if alias:
 723            return alias.columns
 724        return []
 725
 726    @property
 727    def named_selects(self):
 728        return [select.output_name for select in self.selects]
 729
 730
 731class Unionable(Expression):
 732    def union(self, expression, distinct=True, dialect=None, **opts):
 733        """
 734        Builds a UNION expression.
 735
 736        Example:
 737            >>> import sqlglot
 738            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 739            'SELECT * FROM foo UNION SELECT * FROM bla'
 740
 741        Args:
 742            expression (str | Expression): the SQL code string.
 743                If an `Expression` instance is passed, it will be used as-is.
 744            distinct (bool): set the DISTINCT flag if and only if this is true.
 745            dialect (str): the dialect used to parse the input expression.
 746            opts (kwargs): other options to use to parse the input expressions.
 747        Returns:
 748            Union: the Union expression.
 749        """
 750        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 751
 752    def intersect(self, expression, distinct=True, dialect=None, **opts):
 753        """
 754        Builds an INTERSECT expression.
 755
 756        Example:
 757            >>> import sqlglot
 758            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 759            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 760
 761        Args:
 762            expression (str | Expression): the SQL code string.
 763                If an `Expression` instance is passed, it will be used as-is.
 764            distinct (bool): set the DISTINCT flag if and only if this is true.
 765            dialect (str): the dialect used to parse the input expression.
 766            opts (kwargs): other options to use to parse the input expressions.
 767        Returns:
 768            Intersect: the Intersect expression
 769        """
 770        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 771
 772    def except_(self, expression, distinct=True, dialect=None, **opts):
 773        """
 774        Builds an EXCEPT expression.
 775
 776        Example:
 777            >>> import sqlglot
 778            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 779            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 780
 781        Args:
 782            expression (str | Expression): the SQL code string.
 783                If an `Expression` instance is passed, it will be used as-is.
 784            distinct (bool): set the DISTINCT flag if and only if this is true.
 785            dialect (str): the dialect used to parse the input expression.
 786            opts (kwargs): other options to use to parse the input expressions.
 787        Returns:
 788            Except: the Except expression
 789        """
 790        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 791
 792
 793class UDTF(DerivedTable, Unionable):
 794    pass
 795
 796
 797class Cache(Expression):
 798    arg_types = {
 799        "with": False,
 800        "this": True,
 801        "lazy": False,
 802        "options": False,
 803        "expression": False,
 804    }
 805
 806
 807class Uncache(Expression):
 808    arg_types = {"this": True, "exists": False}
 809
 810
 811class Create(Expression):
 812    arg_types = {
 813        "with": False,
 814        "this": True,
 815        "kind": True,
 816        "expression": False,
 817        "exists": False,
 818        "properties": False,
 819        "replace": False,
 820        "unique": False,
 821        "volatile": False,
 822        "indexes": False,
 823        "no_schema_binding": False,
 824        "begin": False,
 825    }
 826
 827
 828class Describe(Expression):
 829    arg_types = {"this": True, "kind": False}
 830
 831
 832class Pragma(Expression):
 833    pass
 834
 835
 836class Set(Expression):
 837    arg_types = {"expressions": False}
 838
 839
 840class SetItem(Expression):
 841    arg_types = {
 842        "this": False,
 843        "expressions": False,
 844        "kind": False,
 845        "collate": False,  # MySQL SET NAMES statement
 846        "global": False,
 847    }
 848
 849
 850class Show(Expression):
 851    arg_types = {
 852        "this": True,
 853        "target": False,
 854        "offset": False,
 855        "limit": False,
 856        "like": False,
 857        "where": False,
 858        "db": False,
 859        "full": False,
 860        "mutex": False,
 861        "query": False,
 862        "channel": False,
 863        "global": False,
 864        "log": False,
 865        "position": False,
 866        "types": False,
 867    }
 868
 869
 870class UserDefinedFunction(Expression):
 871    arg_types = {"this": True, "expressions": False, "wrapped": False}
 872
 873
 874class CharacterSet(Expression):
 875    arg_types = {"this": True, "default": False}
 876
 877
 878class With(Expression):
 879    arg_types = {"expressions": True, "recursive": False}
 880
 881    @property
 882    def recursive(self) -> bool:
 883        return bool(self.args.get("recursive"))
 884
 885
 886class WithinGroup(Expression):
 887    arg_types = {"this": True, "expression": False}
 888
 889
 890class CTE(DerivedTable):
 891    arg_types = {"this": True, "alias": True}
 892
 893
 894class TableAlias(Expression):
 895    arg_types = {"this": False, "columns": False}
 896
 897    @property
 898    def columns(self):
 899        return self.args.get("columns") or []
 900
 901
 902class BitString(Condition):
 903    pass
 904
 905
 906class HexString(Condition):
 907    pass
 908
 909
 910class ByteString(Condition):
 911    pass
 912
 913
 914class Column(Condition):
 915    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
 916
 917    @property
 918    def table(self) -> str:
 919        return self.text("table")
 920
 921    @property
 922    def db(self) -> str:
 923        return self.text("db")
 924
 925    @property
 926    def catalog(self) -> str:
 927        return self.text("catalog")
 928
 929    @property
 930    def output_name(self) -> str:
 931        return self.name
 932
 933    @property
 934    def parts(self) -> t.List[Identifier]:
 935        """Return the parts of a column in order catalog, db, table, name."""
 936        return [part for part in reversed(list(self.args.values())) if part]
 937
 938    def to_dot(self) -> Dot:
 939        """Converts the column into a dot expression."""
 940        parts = self.parts
 941        parent = self.parent
 942
 943        while parent:
 944            if isinstance(parent, Dot):
 945                parts.append(parent.expression)
 946            parent = parent.parent
 947
 948        return Dot.build(parts)
 949
 950
 951class ColumnDef(Expression):
 952    arg_types = {
 953        "this": True,
 954        "kind": False,
 955        "constraints": False,
 956        "exists": False,
 957    }
 958
 959
 960class AlterColumn(Expression):
 961    arg_types = {
 962        "this": True,
 963        "dtype": False,
 964        "collate": False,
 965        "using": False,
 966        "default": False,
 967        "drop": False,
 968    }
 969
 970
 971class RenameTable(Expression):
 972    pass
 973
 974
 975class SetTag(Expression):
 976    arg_types = {"expressions": True, "unset": False}
 977
 978
 979class Comment(Expression):
 980    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
 981
 982
 983class ColumnConstraint(Expression):
 984    arg_types = {"this": False, "kind": True}
 985
 986
 987class ColumnConstraintKind(Expression):
 988    pass
 989
 990
 991class AutoIncrementColumnConstraint(ColumnConstraintKind):
 992    pass
 993
 994
 995class CaseSpecificColumnConstraint(ColumnConstraintKind):
 996    arg_types = {"not_": True}
 997
 998
 999class CharacterSetColumnConstraint(ColumnConstraintKind):
1000    arg_types = {"this": True}
1001
1002
1003class CheckColumnConstraint(ColumnConstraintKind):
1004    pass
1005
1006
1007class CollateColumnConstraint(ColumnConstraintKind):
1008    pass
1009
1010
1011class CommentColumnConstraint(ColumnConstraintKind):
1012    pass
1013
1014
1015class CompressColumnConstraint(ColumnConstraintKind):
1016    pass
1017
1018
1019class DateFormatColumnConstraint(ColumnConstraintKind):
1020    arg_types = {"this": True}
1021
1022
1023class DefaultColumnConstraint(ColumnConstraintKind):
1024    pass
1025
1026
1027class EncodeColumnConstraint(ColumnConstraintKind):
1028    pass
1029
1030
1031class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1032    # this: True -> ALWAYS, this: False -> BY DEFAULT
1033    arg_types = {
1034        "this": False,
1035        "start": False,
1036        "increment": False,
1037        "minvalue": False,
1038        "maxvalue": False,
1039        "cycle": False,
1040    }
1041
1042
1043class InlineLengthColumnConstraint(ColumnConstraintKind):
1044    pass
1045
1046
1047class NotNullColumnConstraint(ColumnConstraintKind):
1048    arg_types = {"allow_null": False}
1049
1050
1051class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1052    arg_types = {"desc": False}
1053
1054
1055class TitleColumnConstraint(ColumnConstraintKind):
1056    pass
1057
1058
1059class UniqueColumnConstraint(ColumnConstraintKind):
1060    arg_types: t.Dict[str, t.Any] = {}
1061
1062
1063class UppercaseColumnConstraint(ColumnConstraintKind):
1064    arg_types: t.Dict[str, t.Any] = {}
1065
1066
1067class PathColumnConstraint(ColumnConstraintKind):
1068    pass
1069
1070
1071class Constraint(Expression):
1072    arg_types = {"this": True, "expressions": True}
1073
1074
1075class Delete(Expression):
1076    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1077
1078    def delete(
1079        self,
1080        table: ExpOrStr,
1081        dialect: DialectType = None,
1082        copy: bool = True,
1083        **opts,
1084    ) -> Delete:
1085        """
1086        Create a DELETE expression or replace the table on an existing DELETE expression.
1087
1088        Example:
1089            >>> delete("tbl").sql()
1090            'DELETE FROM tbl'
1091
1092        Args:
1093            table: the table from which to delete.
1094            dialect: the dialect used to parse the input expression.
1095            copy: if `False`, modify this expression instance in-place.
1096            opts: other options to use to parse the input expressions.
1097
1098        Returns:
1099            Delete: the modified expression.
1100        """
1101        return _apply_builder(
1102            expression=table,
1103            instance=self,
1104            arg="this",
1105            dialect=dialect,
1106            into=Table,
1107            copy=copy,
1108            **opts,
1109        )
1110
1111    def where(
1112        self,
1113        *expressions: ExpOrStr,
1114        append: bool = True,
1115        dialect: DialectType = None,
1116        copy: bool = True,
1117        **opts,
1118    ) -> Delete:
1119        """
1120        Append to or set the WHERE expressions.
1121
1122        Example:
1123            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1124            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1125
1126        Args:
1127            *expressions: the SQL code strings to parse.
1128                If an `Expression` instance is passed, it will be used as-is.
1129                Multiple expressions are combined with an AND operator.
1130            append: if `True`, AND the new expressions to any existing expression.
1131                Otherwise, this resets the expression.
1132            dialect: the dialect used to parse the input expressions.
1133            copy: if `False`, modify this expression instance in-place.
1134            opts: other options to use to parse the input expressions.
1135
1136        Returns:
1137            Delete: the modified expression.
1138        """
1139        return _apply_conjunction_builder(
1140            *expressions,
1141            instance=self,
1142            arg="where",
1143            append=append,
1144            into=Where,
1145            dialect=dialect,
1146            copy=copy,
1147            **opts,
1148        )
1149
1150    def returning(
1151        self,
1152        expression: ExpOrStr,
1153        dialect: DialectType = None,
1154        copy: bool = True,
1155        **opts,
1156    ) -> Delete:
1157        """
1158        Set the RETURNING expression. Not supported by all dialects.
1159
1160        Example:
1161            >>> delete("tbl").returning("*", dialect="postgres").sql()
1162            'DELETE FROM tbl RETURNING *'
1163
1164        Args:
1165            expression: the SQL code strings to parse.
1166                If an `Expression` instance is passed, it will be used as-is.
1167            dialect: the dialect used to parse the input expressions.
1168            copy: if `False`, modify this expression instance in-place.
1169            opts: other options to use to parse the input expressions.
1170
1171        Returns:
1172            Delete: the modified expression.
1173        """
1174        return _apply_builder(
1175            expression=expression,
1176            instance=self,
1177            arg="returning",
1178            prefix="RETURNING",
1179            dialect=dialect,
1180            copy=copy,
1181            into=Returning,
1182            **opts,
1183        )
1184
1185
1186class Drop(Expression):
1187    arg_types = {
1188        "this": False,
1189        "kind": False,
1190        "exists": False,
1191        "temporary": False,
1192        "materialized": False,
1193        "cascade": False,
1194        "constraints": False,
1195    }
1196
1197
1198class Filter(Expression):
1199    arg_types = {"this": True, "expression": True}
1200
1201
1202class Check(Expression):
1203    pass
1204
1205
1206class Directory(Expression):
1207    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1208    arg_types = {"this": True, "local": False, "row_format": False}
1209
1210
1211class ForeignKey(Expression):
1212    arg_types = {
1213        "expressions": True,
1214        "reference": False,
1215        "delete": False,
1216        "update": False,
1217    }
1218
1219
1220class PrimaryKey(Expression):
1221    arg_types = {"expressions": True, "options": False}
1222
1223
1224class Unique(Expression):
1225    arg_types = {"expressions": True}
1226
1227
1228# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1229# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1230class Into(Expression):
1231    arg_types = {"this": True, "temporary": False, "unlogged": False}
1232
1233
1234class From(Expression):
1235    arg_types = {"expressions": True}
1236
1237
1238class Having(Expression):
1239    pass
1240
1241
1242class Hint(Expression):
1243    arg_types = {"expressions": True}
1244
1245
1246class JoinHint(Expression):
1247    arg_types = {"this": True, "expressions": True}
1248
1249
1250class Identifier(Expression):
1251    arg_types = {"this": True, "quoted": False}
1252
1253    @property
1254    def quoted(self):
1255        return bool(self.args.get("quoted"))
1256
1257    @property
1258    def hashable_args(self) -> t.Any:
1259        if self.quoted and any(char.isupper() for char in self.this):
1260            return (self.this, self.quoted)
1261        return self.this.lower()
1262
1263    @property
1264    def output_name(self):
1265        return self.name
1266
1267
1268class Index(Expression):
1269    arg_types = {
1270        "this": False,
1271        "table": False,
1272        "where": False,
1273        "columns": False,
1274        "unique": False,
1275        "primary": False,
1276        "amp": False,  # teradata
1277    }
1278
1279
1280class Insert(Expression):
1281    arg_types = {
1282        "with": False,
1283        "this": True,
1284        "expression": False,
1285        "returning": False,
1286        "overwrite": False,
1287        "exists": False,
1288        "partition": False,
1289        "alternative": False,
1290    }
1291
1292
1293class Returning(Expression):
1294    arg_types = {"expressions": True}
1295
1296
1297# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1298class Introducer(Expression):
1299    arg_types = {"this": True, "expression": True}
1300
1301
1302# national char, like n'utf8'
1303class National(Expression):
1304    pass
1305
1306
1307class LoadData(Expression):
1308    arg_types = {
1309        "this": True,
1310        "local": False,
1311        "overwrite": False,
1312        "inpath": True,
1313        "partition": False,
1314        "input_format": False,
1315        "serde": False,
1316    }
1317
1318
1319class Partition(Expression):
1320    arg_types = {"expressions": True}
1321
1322
1323class Fetch(Expression):
1324    arg_types = {"direction": False, "count": False}
1325
1326
1327class Group(Expression):
1328    arg_types = {
1329        "expressions": False,
1330        "grouping_sets": False,
1331        "cube": False,
1332        "rollup": False,
1333    }
1334
1335
1336class Lambda(Expression):
1337    arg_types = {"this": True, "expressions": True}
1338
1339
1340class Limit(Expression):
1341    arg_types = {"this": False, "expression": True}
1342
1343
1344class Literal(Condition):
1345    arg_types = {"this": True, "is_string": True}
1346
1347    @property
1348    def hashable_args(self) -> t.Any:
1349        return (self.this, self.args.get("is_string"))
1350
1351    @classmethod
1352    def number(cls, number) -> Literal:
1353        return cls(this=str(number), is_string=False)
1354
1355    @classmethod
1356    def string(cls, string) -> Literal:
1357        return cls(this=str(string), is_string=True)
1358
1359    @property
1360    def output_name(self):
1361        return self.name
1362
1363
1364class Join(Expression):
1365    arg_types = {
1366        "this": True,
1367        "on": False,
1368        "side": False,
1369        "kind": False,
1370        "using": False,
1371        "natural": False,
1372    }
1373
1374    @property
1375    def kind(self):
1376        return self.text("kind").upper()
1377
1378    @property
1379    def side(self):
1380        return self.text("side").upper()
1381
1382    @property
1383    def alias_or_name(self):
1384        return self.this.alias_or_name
1385
1386    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1387        """
1388        Append to or set the ON expressions.
1389
1390        Example:
1391            >>> import sqlglot
1392            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1393            'JOIN x ON y = 1'
1394
1395        Args:
1396            *expressions (str | Expression): the SQL code strings to parse.
1397                If an `Expression` instance is passed, it will be used as-is.
1398                Multiple expressions are combined with an AND operator.
1399            append (bool): if `True`, AND the new expressions to any existing expression.
1400                Otherwise, this resets the expression.
1401            dialect (str): the dialect used to parse the input expressions.
1402            copy (bool): if `False`, modify this expression instance in-place.
1403            opts (kwargs): other options to use to parse the input expressions.
1404
1405        Returns:
1406            Join: the modified join expression.
1407        """
1408        join = _apply_conjunction_builder(
1409            *expressions,
1410            instance=self,
1411            arg="on",
1412            append=append,
1413            dialect=dialect,
1414            copy=copy,
1415            **opts,
1416        )
1417
1418        if join.kind == "CROSS":
1419            join.set("kind", None)
1420
1421        return join
1422
1423    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1424        """
1425        Append to or set the USING expressions.
1426
1427        Example:
1428            >>> import sqlglot
1429            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1430            'JOIN x USING (foo, bla)'
1431
1432        Args:
1433            *expressions (str | Expression): the SQL code strings to parse.
1434                If an `Expression` instance is passed, it will be used as-is.
1435            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1436                Otherwise, this resets the expression.
1437            dialect (str): the dialect used to parse the input expressions.
1438            copy (bool): if `False`, modify this expression instance in-place.
1439            opts (kwargs): other options to use to parse the input expressions.
1440
1441        Returns:
1442            Join: the modified join expression.
1443        """
1444        join = _apply_list_builder(
1445            *expressions,
1446            instance=self,
1447            arg="using",
1448            append=append,
1449            dialect=dialect,
1450            copy=copy,
1451            **opts,
1452        )
1453
1454        if join.kind == "CROSS":
1455            join.set("kind", None)
1456
1457        return join
1458
1459
1460class Lateral(UDTF):
1461    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1462
1463
1464class MatchRecognize(Expression):
1465    arg_types = {
1466        "partition_by": False,
1467        "order": False,
1468        "measures": False,
1469        "rows": False,
1470        "after": False,
1471        "pattern": False,
1472        "define": False,
1473    }
1474
1475
1476# Clickhouse FROM FINAL modifier
1477# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1478class Final(Expression):
1479    pass
1480
1481
1482class Offset(Expression):
1483    arg_types = {"this": False, "expression": True}
1484
1485
1486class Order(Expression):
1487    arg_types = {"this": False, "expressions": True}
1488
1489
1490# hive specific sorts
1491# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1492class Cluster(Order):
1493    pass
1494
1495
1496class Distribute(Order):
1497    pass
1498
1499
1500class Sort(Order):
1501    pass
1502
1503
1504class Ordered(Expression):
1505    arg_types = {"this": True, "desc": True, "nulls_first": True}
1506
1507
1508class Property(Expression):
1509    arg_types = {"this": True, "value": True}
1510
1511
1512class AfterJournalProperty(Property):
1513    arg_types = {"no": True, "dual": False, "local": False}
1514
1515
1516class AlgorithmProperty(Property):
1517    arg_types = {"this": True}
1518
1519
1520class AutoIncrementProperty(Property):
1521    arg_types = {"this": True}
1522
1523
1524class BlockCompressionProperty(Property):
1525    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1526
1527
1528class CharacterSetProperty(Property):
1529    arg_types = {"this": True, "default": True}
1530
1531
1532class ChecksumProperty(Property):
1533    arg_types = {"on": False, "default": False}
1534
1535
1536class CollateProperty(Property):
1537    arg_types = {"this": True}
1538
1539
1540class DataBlocksizeProperty(Property):
1541    arg_types = {"size": False, "units": False, "min": False, "default": False}
1542
1543
1544class DefinerProperty(Property):
1545    arg_types = {"this": True}
1546
1547
1548class DistKeyProperty(Property):
1549    arg_types = {"this": True}
1550
1551
1552class DistStyleProperty(Property):
1553    arg_types = {"this": True}
1554
1555
1556class EngineProperty(Property):
1557    arg_types = {"this": True}
1558
1559
1560class ExecuteAsProperty(Property):
1561    arg_types = {"this": True}
1562
1563
1564class ExternalProperty(Property):
1565    arg_types = {"this": False}
1566
1567
1568class FallbackProperty(Property):
1569    arg_types = {"no": True, "protection": False}
1570
1571
1572class FileFormatProperty(Property):
1573    arg_types = {"this": True}
1574
1575
1576class FreespaceProperty(Property):
1577    arg_types = {"this": True, "percent": False}
1578
1579
1580class IsolatedLoadingProperty(Property):
1581    arg_types = {
1582        "no": True,
1583        "concurrent": True,
1584        "for_all": True,
1585        "for_insert": True,
1586        "for_none": True,
1587    }
1588
1589
1590class JournalProperty(Property):
1591    arg_types = {"no": True, "dual": False, "before": False}
1592
1593
1594class LanguageProperty(Property):
1595    arg_types = {"this": True}
1596
1597
1598class LikeProperty(Property):
1599    arg_types = {"this": True, "expressions": False}
1600
1601
1602class LocationProperty(Property):
1603    arg_types = {"this": True}
1604
1605
1606class LockingProperty(Property):
1607    arg_types = {
1608        "this": False,
1609        "kind": True,
1610        "for_or_in": True,
1611        "lock_type": True,
1612        "override": False,
1613    }
1614
1615
1616class LogProperty(Property):
1617    arg_types = {"no": True}
1618
1619
1620class MaterializedProperty(Property):
1621    arg_types = {"this": False}
1622
1623
1624class MergeBlockRatioProperty(Property):
1625    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1626
1627
1628class NoPrimaryIndexProperty(Property):
1629    arg_types = {"this": False}
1630
1631
1632class OnCommitProperty(Property):
1633    arg_type = {"this": False}
1634
1635
1636class PartitionedByProperty(Property):
1637    arg_types = {"this": True}
1638
1639
1640class ReturnsProperty(Property):
1641    arg_types = {"this": True, "is_table": False, "table": False}
1642
1643
1644class RowFormatDelimitedProperty(Property):
1645    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1646    arg_types = {
1647        "fields": False,
1648        "escaped": False,
1649        "collection_items": False,
1650        "map_keys": False,
1651        "lines": False,
1652        "null": False,
1653        "serde": False,
1654    }
1655
1656
1657class RowFormatSerdeProperty(Property):
1658    arg_types = {"this": True}
1659
1660
1661class SchemaCommentProperty(Property):
1662    arg_types = {"this": True}
1663
1664
1665class SerdeProperties(Property):
1666    arg_types = {"expressions": True}
1667
1668
1669class SetProperty(Property):
1670    arg_types = {"multi": True}
1671
1672
1673class SortKeyProperty(Property):
1674    arg_types = {"this": True, "compound": False}
1675
1676
1677class SqlSecurityProperty(Property):
1678    arg_types = {"definer": True}
1679
1680
1681class TableFormatProperty(Property):
1682    arg_types = {"this": True}
1683
1684
1685class TemporaryProperty(Property):
1686    arg_types = {"global_": True}
1687
1688
1689class TransientProperty(Property):
1690    arg_types = {"this": False}
1691
1692
1693class VolatilityProperty(Property):
1694    arg_types = {"this": True}
1695
1696
1697class WithDataProperty(Property):
1698    arg_types = {"no": True, "statistics": False}
1699
1700
1701class WithJournalTableProperty(Property):
1702    arg_types = {"this": True}
1703
1704
1705class Properties(Expression):
1706    arg_types = {"expressions": True}
1707
1708    NAME_TO_PROPERTY = {
1709        "ALGORITHM": AlgorithmProperty,
1710        "AUTO_INCREMENT": AutoIncrementProperty,
1711        "CHARACTER SET": CharacterSetProperty,
1712        "COLLATE": CollateProperty,
1713        "COMMENT": SchemaCommentProperty,
1714        "DEFINER": DefinerProperty,
1715        "DISTKEY": DistKeyProperty,
1716        "DISTSTYLE": DistStyleProperty,
1717        "ENGINE": EngineProperty,
1718        "EXECUTE AS": ExecuteAsProperty,
1719        "FORMAT": FileFormatProperty,
1720        "LANGUAGE": LanguageProperty,
1721        "LOCATION": LocationProperty,
1722        "PARTITIONED_BY": PartitionedByProperty,
1723        "RETURNS": ReturnsProperty,
1724        "SORTKEY": SortKeyProperty,
1725        "TABLE_FORMAT": TableFormatProperty,
1726    }
1727
1728    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1729
1730    # CREATE property locations
1731    # Form: schema specified
1732    #   create [POST_CREATE]
1733    #     table a [POST_NAME]
1734    #     (b int) [POST_SCHEMA]
1735    #     with ([POST_WITH])
1736    #     index (b) [POST_INDEX]
1737    #
1738    # Form: alias selection
1739    #   create [POST_CREATE]
1740    #     table a [POST_NAME]
1741    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1742    #     index (c) [POST_INDEX]
1743    class Location(AutoName):
1744        POST_CREATE = auto()
1745        POST_NAME = auto()
1746        POST_SCHEMA = auto()
1747        POST_WITH = auto()
1748        POST_ALIAS = auto()
1749        POST_EXPRESSION = auto()
1750        POST_INDEX = auto()
1751        UNSUPPORTED = auto()
1752
1753    @classmethod
1754    def from_dict(cls, properties_dict) -> Properties:
1755        expressions = []
1756        for key, value in properties_dict.items():
1757            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1758            if property_cls:
1759                expressions.append(property_cls(this=convert(value)))
1760            else:
1761                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1762
1763        return cls(expressions=expressions)
1764
1765
1766class Qualify(Expression):
1767    pass
1768
1769
1770# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1771class Return(Expression):
1772    pass
1773
1774
1775class Reference(Expression):
1776    arg_types = {"this": True, "expressions": False, "options": False}
1777
1778
1779class Tuple(Expression):
1780    arg_types = {"expressions": False}
1781
1782
1783class Subqueryable(Unionable):
1784    def subquery(self, alias=None, copy=True) -> Subquery:
1785        """
1786        Convert this expression to an aliased expression that can be used as a Subquery.
1787
1788        Example:
1789            >>> subquery = Select().select("x").from_("tbl").subquery()
1790            >>> Select().select("x").from_(subquery).sql()
1791            'SELECT x FROM (SELECT x FROM tbl)'
1792
1793        Args:
1794            alias (str | Identifier): an optional alias for the subquery
1795            copy (bool): if `False`, modify this expression instance in-place.
1796
1797        Returns:
1798            Alias: the subquery
1799        """
1800        instance = _maybe_copy(self, copy)
1801        return Subquery(
1802            this=instance,
1803            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1804        )
1805
1806    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1807        raise NotImplementedError
1808
1809    @property
1810    def ctes(self):
1811        with_ = self.args.get("with")
1812        if not with_:
1813            return []
1814        return with_.expressions
1815
1816    @property
1817    def selects(self):
1818        raise NotImplementedError("Subqueryable objects must implement `selects`")
1819
1820    @property
1821    def named_selects(self):
1822        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1823
1824    def with_(
1825        self,
1826        alias,
1827        as_,
1828        recursive=None,
1829        append=True,
1830        dialect=None,
1831        copy=True,
1832        **opts,
1833    ):
1834        """
1835        Append to or set the common table expressions.
1836
1837        Example:
1838            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1839            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1840
1841        Args:
1842            alias (str | Expression): the SQL code string to parse as the table name.
1843                If an `Expression` instance is passed, this is used as-is.
1844            as_ (str | Expression): the SQL code string to parse as the table expression.
1845                If an `Expression` instance is passed, it will be used as-is.
1846            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1847            append (bool): if `True`, add to any existing expressions.
1848                Otherwise, this resets the expressions.
1849            dialect (str): the dialect used to parse the input expression.
1850            copy (bool): if `False`, modify this expression instance in-place.
1851            opts (kwargs): other options to use to parse the input expressions.
1852
1853        Returns:
1854            Select: the modified expression.
1855        """
1856        alias_expression = maybe_parse(
1857            alias,
1858            dialect=dialect,
1859            into=TableAlias,
1860            **opts,
1861        )
1862        as_expression = maybe_parse(
1863            as_,
1864            dialect=dialect,
1865            **opts,
1866        )
1867        cte = CTE(
1868            this=as_expression,
1869            alias=alias_expression,
1870        )
1871        return _apply_child_list_builder(
1872            cte,
1873            instance=self,
1874            arg="with",
1875            append=append,
1876            copy=copy,
1877            into=With,
1878            properties={"recursive": recursive or False},
1879        )
1880
1881
1882QUERY_MODIFIERS = {
1883    "match": False,
1884    "laterals": False,
1885    "joins": False,
1886    "pivots": False,
1887    "where": False,
1888    "group": False,
1889    "having": False,
1890    "qualify": False,
1891    "windows": False,
1892    "distribute": False,
1893    "sort": False,
1894    "cluster": False,
1895    "order": False,
1896    "limit": False,
1897    "offset": False,
1898    "lock": False,
1899    "sample": False,
1900}
1901
1902
1903class Table(Expression):
1904    arg_types = {
1905        "this": True,
1906        "alias": False,
1907        "db": False,
1908        "catalog": False,
1909        "laterals": False,
1910        "joins": False,
1911        "pivots": False,
1912        "hints": False,
1913        "system_time": False,
1914    }
1915
1916    @property
1917    def db(self) -> str:
1918        return self.text("db")
1919
1920    @property
1921    def catalog(self) -> str:
1922        return self.text("catalog")
1923
1924
1925# See the TSQL "Querying data in a system-versioned temporal table" page
1926class SystemTime(Expression):
1927    arg_types = {
1928        "this": False,
1929        "expression": False,
1930        "kind": True,
1931    }
1932
1933
1934class Union(Subqueryable):
1935    arg_types = {
1936        "with": False,
1937        "this": True,
1938        "expression": True,
1939        "distinct": False,
1940        **QUERY_MODIFIERS,
1941    }
1942
1943    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1944        """
1945        Set the LIMIT expression.
1946
1947        Example:
1948            >>> select("1").union(select("1")).limit(1).sql()
1949            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1950
1951        Args:
1952            expression (str | int | Expression): the SQL code string to parse.
1953                This can also be an integer.
1954                If a `Limit` instance is passed, this is used as-is.
1955                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1956            dialect (str): the dialect used to parse the input expression.
1957            copy (bool): if `False`, modify this expression instance in-place.
1958            opts (kwargs): other options to use to parse the input expressions.
1959
1960        Returns:
1961            Select: The limited subqueryable.
1962        """
1963        return (
1964            select("*")
1965            .from_(self.subquery(alias="_l_0", copy=copy))
1966            .limit(expression, dialect=dialect, copy=False, **opts)
1967        )
1968
1969    def select(
1970        self,
1971        *expressions: ExpOrStr,
1972        append: bool = True,
1973        dialect: DialectType = None,
1974        copy: bool = True,
1975        **opts,
1976    ) -> Union:
1977        """Append to or set the SELECT of the union recursively.
1978
1979        Example:
1980            >>> from sqlglot import parse_one
1981            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1982            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1983
1984        Args:
1985            *expressions: the SQL code strings to parse.
1986                If an `Expression` instance is passed, it will be used as-is.
1987            append: if `True`, add to any existing expressions.
1988                Otherwise, this resets the expressions.
1989            dialect: the dialect used to parse the input expressions.
1990            copy: if `False`, modify this expression instance in-place.
1991            opts: other options to use to parse the input expressions.
1992
1993        Returns:
1994            Union: the modified expression.
1995        """
1996        this = self.copy() if copy else self
1997        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1998        this.expression.unnest().select(
1999            *expressions, append=append, dialect=dialect, copy=False, **opts
2000        )
2001        return this
2002
2003    @property
2004    def named_selects(self):
2005        return self.this.unnest().named_selects
2006
2007    @property
2008    def is_star(self) -> bool:
2009        return self.this.is_star or self.expression.is_star
2010
2011    @property
2012    def selects(self):
2013        return self.this.unnest().selects
2014
2015    @property
2016    def left(self):
2017        return self.this
2018
2019    @property
2020    def right(self):
2021        return self.expression
2022
2023
2024class Except(Union):
2025    pass
2026
2027
2028class Intersect(Union):
2029    pass
2030
2031
2032class Unnest(UDTF):
2033    arg_types = {
2034        "expressions": True,
2035        "ordinality": False,
2036        "alias": False,
2037        "offset": False,
2038    }
2039
2040
2041class Update(Expression):
2042    arg_types = {
2043        "with": False,
2044        "this": False,
2045        "expressions": True,
2046        "from": False,
2047        "where": False,
2048        "returning": False,
2049    }
2050
2051
2052class Values(UDTF):
2053    arg_types = {
2054        "expressions": True,
2055        "ordinality": False,
2056        "alias": False,
2057    }
2058
2059
2060class Var(Expression):
2061    pass
2062
2063
2064class Schema(Expression):
2065    arg_types = {"this": False, "expressions": False}
2066
2067
2068# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2069# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2070class Lock(Expression):
2071    arg_types = {"update": True}
2072
2073
2074class Select(Subqueryable):
2075    arg_types = {
2076        "with": False,
2077        "kind": False,
2078        "expressions": False,
2079        "hint": False,
2080        "distinct": False,
2081        "into": False,
2082        "from": False,
2083        **QUERY_MODIFIERS,
2084    }
2085
2086    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2087        """
2088        Set the FROM expression.
2089
2090        Example:
2091            >>> Select().from_("tbl").select("x").sql()
2092            'SELECT x FROM tbl'
2093
2094        Args:
2095            *expressions (str | Expression): the SQL code strings to parse.
2096                If a `From` instance is passed, this is used as-is.
2097                If another `Expression` instance is passed, it will be wrapped in a `From`.
2098            append (bool): if `True`, add to any existing expressions.
2099                Otherwise, this flattens all the `From` expression into a single expression.
2100            dialect (str): the dialect used to parse the input expression.
2101            copy (bool): if `False`, modify this expression instance in-place.
2102            opts (kwargs): other options to use to parse the input expressions.
2103
2104        Returns:
2105            Select: the modified expression.
2106        """
2107        return _apply_child_list_builder(
2108            *expressions,
2109            instance=self,
2110            arg="from",
2111            append=append,
2112            copy=copy,
2113            prefix="FROM",
2114            into=From,
2115            dialect=dialect,
2116            **opts,
2117        )
2118
2119    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2120        """
2121        Set the GROUP BY expression.
2122
2123        Example:
2124            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2125            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2126
2127        Args:
2128            *expressions (str | Expression): the SQL code strings to parse.
2129                If a `Group` instance is passed, this is used as-is.
2130                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2131                If nothing is passed in then a group by is not applied to the expression
2132            append (bool): if `True`, add to any existing expressions.
2133                Otherwise, this flattens all the `Group` expression into a single expression.
2134            dialect (str): the dialect used to parse the input expression.
2135            copy (bool): if `False`, modify this expression instance in-place.
2136            opts (kwargs): other options to use to parse the input expressions.
2137
2138        Returns:
2139            Select: the modified expression.
2140        """
2141        if not expressions:
2142            return self if not copy else self.copy()
2143        return _apply_child_list_builder(
2144            *expressions,
2145            instance=self,
2146            arg="group",
2147            append=append,
2148            copy=copy,
2149            prefix="GROUP BY",
2150            into=Group,
2151            dialect=dialect,
2152            **opts,
2153        )
2154
2155    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2156        """
2157        Set the ORDER BY expression.
2158
2159        Example:
2160            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2161            'SELECT x FROM tbl ORDER BY x DESC'
2162
2163        Args:
2164            *expressions (str | Expression): the SQL code strings to parse.
2165                If a `Group` instance is passed, this is used as-is.
2166                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2167            append (bool): if `True`, add to any existing expressions.
2168                Otherwise, this flattens all the `Order` expression into a single expression.
2169            dialect (str): the dialect used to parse the input expression.
2170            copy (bool): if `False`, modify this expression instance in-place.
2171            opts (kwargs): other options to use to parse the input expressions.
2172
2173        Returns:
2174            Select: the modified expression.
2175        """
2176        return _apply_child_list_builder(
2177            *expressions,
2178            instance=self,
2179            arg="order",
2180            append=append,
2181            copy=copy,
2182            prefix="ORDER BY",
2183            into=Order,
2184            dialect=dialect,
2185            **opts,
2186        )
2187
2188    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2189        """
2190        Set the SORT BY expression.
2191
2192        Example:
2193            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2194            'SELECT x FROM tbl SORT BY x DESC'
2195
2196        Args:
2197            *expressions (str | Expression): the SQL code strings to parse.
2198                If a `Group` instance is passed, this is used as-is.
2199                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2200            append (bool): if `True`, add to any existing expressions.
2201                Otherwise, this flattens all the `Order` expression into a single expression.
2202            dialect (str): the dialect used to parse the input expression.
2203            copy (bool): if `False`, modify this expression instance in-place.
2204            opts (kwargs): other options to use to parse the input expressions.
2205
2206        Returns:
2207            Select: the modified expression.
2208        """
2209        return _apply_child_list_builder(
2210            *expressions,
2211            instance=self,
2212            arg="sort",
2213            append=append,
2214            copy=copy,
2215            prefix="SORT BY",
2216            into=Sort,
2217            dialect=dialect,
2218            **opts,
2219        )
2220
2221    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2222        """
2223        Set the CLUSTER BY expression.
2224
2225        Example:
2226            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2227            'SELECT x FROM tbl CLUSTER BY x DESC'
2228
2229        Args:
2230            *expressions (str | Expression): the SQL code strings to parse.
2231                If a `Group` instance is passed, this is used as-is.
2232                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2233            append (bool): if `True`, add to any existing expressions.
2234                Otherwise, this flattens all the `Order` expression into a single expression.
2235            dialect (str): the dialect used to parse the input expression.
2236            copy (bool): if `False`, modify this expression instance in-place.
2237            opts (kwargs): other options to use to parse the input expressions.
2238
2239        Returns:
2240            Select: the modified expression.
2241        """
2242        return _apply_child_list_builder(
2243            *expressions,
2244            instance=self,
2245            arg="cluster",
2246            append=append,
2247            copy=copy,
2248            prefix="CLUSTER BY",
2249            into=Cluster,
2250            dialect=dialect,
2251            **opts,
2252        )
2253
2254    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2255        """
2256        Set the LIMIT expression.
2257
2258        Example:
2259            >>> Select().from_("tbl").select("x").limit(10).sql()
2260            'SELECT x FROM tbl LIMIT 10'
2261
2262        Args:
2263            expression (str | int | Expression): the SQL code string to parse.
2264                This can also be an integer.
2265                If a `Limit` instance is passed, this is used as-is.
2266                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2267            dialect (str): the dialect used to parse the input expression.
2268            copy (bool): if `False`, modify this expression instance in-place.
2269            opts (kwargs): other options to use to parse the input expressions.
2270
2271        Returns:
2272            Select: the modified expression.
2273        """
2274        return _apply_builder(
2275            expression=expression,
2276            instance=self,
2277            arg="limit",
2278            into=Limit,
2279            prefix="LIMIT",
2280            dialect=dialect,
2281            copy=copy,
2282            **opts,
2283        )
2284
2285    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2286        """
2287        Set the OFFSET expression.
2288
2289        Example:
2290            >>> Select().from_("tbl").select("x").offset(10).sql()
2291            'SELECT x FROM tbl OFFSET 10'
2292
2293        Args:
2294            expression (str | int | Expression): the SQL code string to parse.
2295                This can also be an integer.
2296                If a `Offset` instance is passed, this is used as-is.
2297                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2298            dialect (str): the dialect used to parse the input expression.
2299            copy (bool): if `False`, modify this expression instance in-place.
2300            opts (kwargs): other options to use to parse the input expressions.
2301
2302        Returns:
2303            Select: the modified expression.
2304        """
2305        return _apply_builder(
2306            expression=expression,
2307            instance=self,
2308            arg="offset",
2309            into=Offset,
2310            prefix="OFFSET",
2311            dialect=dialect,
2312            copy=copy,
2313            **opts,
2314        )
2315
2316    def select(
2317        self,
2318        *expressions: ExpOrStr,
2319        append: bool = True,
2320        dialect: DialectType = None,
2321        copy: bool = True,
2322        **opts,
2323    ) -> Select:
2324        """
2325        Append to or set the SELECT expressions.
2326
2327        Example:
2328            >>> Select().select("x", "y").sql()
2329            'SELECT x, y'
2330
2331        Args:
2332            *expressions: the SQL code strings to parse.
2333                If an `Expression` instance is passed, it will be used as-is.
2334            append: if `True`, add to any existing expressions.
2335                Otherwise, this resets the expressions.
2336            dialect: the dialect used to parse the input expressions.
2337            copy: if `False`, modify this expression instance in-place.
2338            opts: other options to use to parse the input expressions.
2339
2340        Returns:
2341            Select: the modified expression.
2342        """
2343        return _apply_list_builder(
2344            *expressions,
2345            instance=self,
2346            arg="expressions",
2347            append=append,
2348            dialect=dialect,
2349            copy=copy,
2350            **opts,
2351        )
2352
2353    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2354        """
2355        Append to or set the LATERAL expressions.
2356
2357        Example:
2358            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2359            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2360
2361        Args:
2362            *expressions (str | Expression): the SQL code strings to parse.
2363                If an `Expression` instance is passed, it will be used as-is.
2364            append (bool): if `True`, add to any existing expressions.
2365                Otherwise, this resets the expressions.
2366            dialect (str): the dialect used to parse the input expressions.
2367            copy (bool): if `False`, modify this expression instance in-place.
2368            opts (kwargs): other options to use to parse the input expressions.
2369
2370        Returns:
2371            Select: the modified expression.
2372        """
2373        return _apply_list_builder(
2374            *expressions,
2375            instance=self,
2376            arg="laterals",
2377            append=append,
2378            into=Lateral,
2379            prefix="LATERAL VIEW",
2380            dialect=dialect,
2381            copy=copy,
2382            **opts,
2383        )
2384
2385    def join(
2386        self,
2387        expression,
2388        on=None,
2389        using=None,
2390        append=True,
2391        join_type=None,
2392        join_alias=None,
2393        dialect=None,
2394        copy=True,
2395        **opts,
2396    ) -> Select:
2397        """
2398        Append to or set the JOIN expressions.
2399
2400        Example:
2401            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2402            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2403
2404            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2405            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2406
2407            Use `join_type` to change the type of join:
2408
2409            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2410            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2411
2412        Args:
2413            expression (str | Expression): the SQL code string to parse.
2414                If an `Expression` instance is passed, it will be used as-is.
2415            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2416                If an `Expression` instance is passed, it will be used as-is.
2417            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2418                If an `Expression` instance is passed, it will be used as-is.
2419            append (bool): if `True`, add to any existing expressions.
2420                Otherwise, this resets the expressions.
2421            join_type (str): If set, alter the parsed join type
2422            dialect (str): the dialect used to parse the input expressions.
2423            copy (bool): if `False`, modify this expression instance in-place.
2424            opts (kwargs): other options to use to parse the input expressions.
2425
2426        Returns:
2427            Select: the modified expression.
2428        """
2429        parse_args = {"dialect": dialect, **opts}
2430
2431        try:
2432            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2433        except ParseError:
2434            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2435
2436        join = expression if isinstance(expression, Join) else Join(this=expression)
2437
2438        if isinstance(join.this, Select):
2439            join.this.replace(join.this.subquery())
2440
2441        if join_type:
2442            natural: t.Optional[Token]
2443            side: t.Optional[Token]
2444            kind: t.Optional[Token]
2445
2446            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2447
2448            if natural:
2449                join.set("natural", True)
2450            if side:
2451                join.set("side", side.text)
2452            if kind:
2453                join.set("kind", kind.text)
2454
2455        if on:
2456            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2457            join.set("on", on)
2458
2459        if using:
2460            join = _apply_list_builder(
2461                *ensure_collection(using),
2462                instance=join,
2463                arg="using",
2464                append=append,
2465                copy=copy,
2466                **opts,
2467            )
2468
2469        if join_alias:
2470            join.set("this", alias_(join.this, join_alias, table=True))
2471        return _apply_list_builder(
2472            join,
2473            instance=self,
2474            arg="joins",
2475            append=append,
2476            copy=copy,
2477            **opts,
2478        )
2479
2480    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2481        """
2482        Append to or set the WHERE expressions.
2483
2484        Example:
2485            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2486            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2487
2488        Args:
2489            *expressions (str | Expression): the SQL code strings to parse.
2490                If an `Expression` instance is passed, it will be used as-is.
2491                Multiple expressions are combined with an AND operator.
2492            append (bool): if `True`, AND the new expressions to any existing expression.
2493                Otherwise, this resets the expression.
2494            dialect (str): the dialect used to parse the input expressions.
2495            copy (bool): if `False`, modify this expression instance in-place.
2496            opts (kwargs): other options to use to parse the input expressions.
2497
2498        Returns:
2499            Select: the modified expression.
2500        """
2501        return _apply_conjunction_builder(
2502            *expressions,
2503            instance=self,
2504            arg="where",
2505            append=append,
2506            into=Where,
2507            dialect=dialect,
2508            copy=copy,
2509            **opts,
2510        )
2511
2512    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2513        """
2514        Append to or set the HAVING expressions.
2515
2516        Example:
2517            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2518            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2519
2520        Args:
2521            *expressions (str | Expression): the SQL code strings to parse.
2522                If an `Expression` instance is passed, it will be used as-is.
2523                Multiple expressions are combined with an AND operator.
2524            append (bool): if `True`, AND the new expressions to any existing expression.
2525                Otherwise, this resets the expression.
2526            dialect (str): the dialect used to parse the input expressions.
2527            copy (bool): if `False`, modify this expression instance in-place.
2528            opts (kwargs): other options to use to parse the input expressions.
2529
2530        Returns:
2531            Select: the modified expression.
2532        """
2533        return _apply_conjunction_builder(
2534            *expressions,
2535            instance=self,
2536            arg="having",
2537            append=append,
2538            into=Having,
2539            dialect=dialect,
2540            copy=copy,
2541            **opts,
2542        )
2543
2544    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2545        return _apply_list_builder(
2546            *expressions,
2547            instance=self,
2548            arg="windows",
2549            append=append,
2550            into=Window,
2551            dialect=dialect,
2552            copy=copy,
2553            **opts,
2554        )
2555
2556    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2557        return _apply_conjunction_builder(
2558            *expressions,
2559            instance=self,
2560            arg="qualify",
2561            append=append,
2562            into=Qualify,
2563            dialect=dialect,
2564            copy=copy,
2565            **opts,
2566        )
2567
2568    def distinct(self, distinct=True, copy=True) -> Select:
2569        """
2570        Set the OFFSET expression.
2571
2572        Example:
2573            >>> Select().from_("tbl").select("x").distinct().sql()
2574            'SELECT DISTINCT x FROM tbl'
2575
2576        Args:
2577            distinct (bool): whether the Select should be distinct
2578            copy (bool): if `False`, modify this expression instance in-place.
2579
2580        Returns:
2581            Select: the modified expression.
2582        """
2583        instance = _maybe_copy(self, copy)
2584        instance.set("distinct", Distinct() if distinct else None)
2585        return instance
2586
2587    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2588        """
2589        Convert this expression to a CREATE TABLE AS statement.
2590
2591        Example:
2592            >>> Select().select("*").from_("tbl").ctas("x").sql()
2593            'CREATE TABLE x AS SELECT * FROM tbl'
2594
2595        Args:
2596            table (str | Expression): the SQL code string to parse as the table name.
2597                If another `Expression` instance is passed, it will be used as-is.
2598            properties (dict): an optional mapping of table properties
2599            dialect (str): the dialect used to parse the input table.
2600            copy (bool): if `False`, modify this expression instance in-place.
2601            opts (kwargs): other options to use to parse the input table.
2602
2603        Returns:
2604            Create: the CREATE TABLE AS expression
2605        """
2606        instance = _maybe_copy(self, copy)
2607        table_expression = maybe_parse(
2608            table,
2609            into=Table,
2610            dialect=dialect,
2611            **opts,
2612        )
2613        properties_expression = None
2614        if properties:
2615            properties_expression = Properties.from_dict(properties)
2616
2617        return Create(
2618            this=table_expression,
2619            kind="table",
2620            expression=instance,
2621            properties=properties_expression,
2622        )
2623
2624    def lock(self, update: bool = True, copy: bool = True) -> Select:
2625        """
2626        Set the locking read mode for this expression.
2627
2628        Examples:
2629            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2630            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2631
2632            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2633            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2634
2635        Args:
2636            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2637            copy: if `False`, modify this expression instance in-place.
2638
2639        Returns:
2640            The modified expression.
2641        """
2642
2643        inst = _maybe_copy(self, copy)
2644        inst.set("lock", Lock(update=update))
2645
2646        return inst
2647
2648    @property
2649    def named_selects(self) -> t.List[str]:
2650        return [e.output_name for e in self.expressions if e.alias_or_name]
2651
2652    @property
2653    def is_star(self) -> bool:
2654        return any(expression.is_star for expression in self.expressions)
2655
2656    @property
2657    def selects(self) -> t.List[Expression]:
2658        return self.expressions
2659
2660
2661class Subquery(DerivedTable, Unionable):
2662    arg_types = {
2663        "this": True,
2664        "alias": False,
2665        "with": False,
2666        **QUERY_MODIFIERS,
2667    }
2668
2669    def unnest(self):
2670        """
2671        Returns the first non subquery.
2672        """
2673        expression = self
2674        while isinstance(expression, Subquery):
2675            expression = expression.this
2676        return expression
2677
2678    @property
2679    def is_star(self) -> bool:
2680        return self.this.is_star
2681
2682    @property
2683    def output_name(self):
2684        return self.alias
2685
2686
2687class TableSample(Expression):
2688    arg_types = {
2689        "this": False,
2690        "method": False,
2691        "bucket_numerator": False,
2692        "bucket_denominator": False,
2693        "bucket_field": False,
2694        "percent": False,
2695        "rows": False,
2696        "size": False,
2697        "seed": False,
2698        "kind": False,
2699    }
2700
2701
2702class Tag(Expression):
2703    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2704
2705    arg_types = {
2706        "this": False,
2707        "prefix": False,
2708        "postfix": False,
2709    }
2710
2711
2712class Pivot(Expression):
2713    arg_types = {
2714        "this": False,
2715        "alias": False,
2716        "expressions": True,
2717        "field": True,
2718        "unpivot": True,
2719    }
2720
2721
2722class Window(Expression):
2723    arg_types = {
2724        "this": True,
2725        "partition_by": False,
2726        "order": False,
2727        "spec": False,
2728        "alias": False,
2729    }
2730
2731
2732class WindowSpec(Expression):
2733    arg_types = {
2734        "kind": False,
2735        "start": False,
2736        "start_side": False,
2737        "end": False,
2738        "end_side": False,
2739    }
2740
2741
2742class Where(Expression):
2743    pass
2744
2745
2746class Star(Expression):
2747    arg_types = {"except": False, "replace": False}
2748
2749    @property
2750    def name(self) -> str:
2751        return "*"
2752
2753    @property
2754    def output_name(self):
2755        return self.name
2756
2757
2758class Parameter(Expression):
2759    arg_types = {"this": True, "wrapped": False}
2760
2761
2762class SessionParameter(Expression):
2763    arg_types = {"this": True, "kind": False}
2764
2765
2766class Placeholder(Expression):
2767    arg_types = {"this": False}
2768
2769
2770class Null(Condition):
2771    arg_types: t.Dict[str, t.Any] = {}
2772
2773    @property
2774    def name(self) -> str:
2775        return "NULL"
2776
2777
2778class Boolean(Condition):
2779    pass
2780
2781
2782class DataType(Expression):
2783    arg_types = {
2784        "this": True,
2785        "expressions": False,
2786        "nested": False,
2787        "values": False,
2788        "prefix": False,
2789    }
2790
2791    class Type(AutoName):
2792        CHAR = auto()
2793        NCHAR = auto()
2794        VARCHAR = auto()
2795        NVARCHAR = auto()
2796        TEXT = auto()
2797        MEDIUMTEXT = auto()
2798        LONGTEXT = auto()
2799        MEDIUMBLOB = auto()
2800        LONGBLOB = auto()
2801        BINARY = auto()
2802        VARBINARY = auto()
2803        INT = auto()
2804        UINT = auto()
2805        TINYINT = auto()
2806        UTINYINT = auto()
2807        SMALLINT = auto()
2808        USMALLINT = auto()
2809        BIGINT = auto()
2810        UBIGINT = auto()
2811        FLOAT = auto()
2812        DOUBLE = auto()
2813        DECIMAL = auto()
2814        BIT = auto()
2815        BOOLEAN = auto()
2816        JSON = auto()
2817        JSONB = auto()
2818        INTERVAL = auto()
2819        TIME = auto()
2820        TIMESTAMP = auto()
2821        TIMESTAMPTZ = auto()
2822        TIMESTAMPLTZ = auto()
2823        DATE = auto()
2824        DATETIME = auto()
2825        ARRAY = auto()
2826        MAP = auto()
2827        UUID = auto()
2828        GEOGRAPHY = auto()
2829        GEOMETRY = auto()
2830        STRUCT = auto()
2831        NULLABLE = auto()
2832        HLLSKETCH = auto()
2833        HSTORE = auto()
2834        SUPER = auto()
2835        SERIAL = auto()
2836        SMALLSERIAL = auto()
2837        BIGSERIAL = auto()
2838        XML = auto()
2839        UNIQUEIDENTIFIER = auto()
2840        MONEY = auto()
2841        SMALLMONEY = auto()
2842        ROWVERSION = auto()
2843        IMAGE = auto()
2844        VARIANT = auto()
2845        OBJECT = auto()
2846        INET = auto()
2847        NULL = auto()
2848        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2849
2850    TEXT_TYPES = {
2851        Type.CHAR,
2852        Type.NCHAR,
2853        Type.VARCHAR,
2854        Type.NVARCHAR,
2855        Type.TEXT,
2856    }
2857
2858    INTEGER_TYPES = {
2859        Type.INT,
2860        Type.TINYINT,
2861        Type.SMALLINT,
2862        Type.BIGINT,
2863    }
2864
2865    FLOAT_TYPES = {
2866        Type.FLOAT,
2867        Type.DOUBLE,
2868    }
2869
2870    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2871
2872    TEMPORAL_TYPES = {
2873        Type.TIMESTAMP,
2874        Type.TIMESTAMPTZ,
2875        Type.TIMESTAMPLTZ,
2876        Type.DATE,
2877        Type.DATETIME,
2878    }
2879
2880    @classmethod
2881    def build(
2882        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2883    ) -> DataType:
2884        from sqlglot import parse_one
2885
2886        if isinstance(dtype, str):
2887            if dtype.upper() in cls.Type.__members__:
2888                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2889            else:
2890                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2891            if data_type_exp is None:
2892                raise ValueError(f"Unparsable data type value: {dtype}")
2893        elif isinstance(dtype, DataType.Type):
2894            data_type_exp = DataType(this=dtype)
2895        elif isinstance(dtype, DataType):
2896            return dtype
2897        else:
2898            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2899        return DataType(**{**data_type_exp.args, **kwargs})
2900
2901    def is_type(self, dtype: DataType.Type) -> bool:
2902        return self.this == dtype
2903
2904
2905# https://www.postgresql.org/docs/15/datatype-pseudo.html
2906class PseudoType(Expression):
2907    pass
2908
2909
2910class StructKwarg(Expression):
2911    arg_types = {"this": True, "expression": True}
2912
2913
2914# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
2915class SubqueryPredicate(Predicate):
2916    pass
2917
2918
2919class All(SubqueryPredicate):
2920    pass
2921
2922
2923class Any(SubqueryPredicate):
2924    pass
2925
2926
2927class Exists(SubqueryPredicate):
2928    pass
2929
2930
2931# Commands to interact with the databases or engines. For most of the command
2932# expressions we parse whatever comes after the command's name as a string.
2933class Command(Expression):
2934    arg_types = {"this": True, "expression": False}
2935
2936
2937class Transaction(Expression):
2938    arg_types = {"this": False, "modes": False}
2939
2940
2941class Commit(Expression):
2942    arg_types = {"chain": False}
2943
2944
2945class Rollback(Expression):
2946    arg_types = {"savepoint": False}
2947
2948
2949class AlterTable(Expression):
2950    arg_types = {"this": True, "actions": True, "exists": False}
2951
2952
2953class AddConstraint(Expression):
2954    arg_types = {"this": False, "expression": False, "enforced": False}
2955
2956
2957class DropPartition(Expression):
2958    arg_types = {"expressions": True, "exists": False}
2959
2960
2961# Binary expressions like (ADD a b)
2962class Binary(Expression):
2963    arg_types = {"this": True, "expression": True}
2964
2965    @property
2966    def left(self):
2967        return self.this
2968
2969    @property
2970    def right(self):
2971        return self.expression
2972
2973
2974class Add(Binary):
2975    pass
2976
2977
2978class Connector(Binary, Condition):
2979    pass
2980
2981
2982class And(Connector):
2983    pass
2984
2985
2986class Or(Connector):
2987    pass
2988
2989
2990class BitwiseAnd(Binary):
2991    pass
2992
2993
2994class BitwiseLeftShift(Binary):
2995    pass
2996
2997
2998class BitwiseOr(Binary):
2999    pass
3000
3001
3002class BitwiseRightShift(Binary):
3003    pass
3004
3005
3006class BitwiseXor(Binary):
3007    pass
3008
3009
3010class Div(Binary):
3011    pass
3012
3013
3014class Overlaps(Binary):
3015    pass
3016
3017
3018class Dot(Binary):
3019    @property
3020    def name(self) -> str:
3021        return self.expression.name
3022
3023    @classmethod
3024    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3025        """Build a Dot object with a sequence of expressions."""
3026        if len(expressions) < 2:
3027            raise ValueError(f"Dot requires >= 2 expressions.")
3028
3029        a, b, *expressions = expressions
3030        dot = Dot(this=a, expression=b)
3031
3032        for expression in expressions:
3033            dot = Dot(this=dot, expression=expression)
3034
3035        return dot
3036
3037
3038class DPipe(Binary):
3039    pass
3040
3041
3042class EQ(Binary, Predicate):
3043    pass
3044
3045
3046class NullSafeEQ(Binary, Predicate):
3047    pass
3048
3049
3050class NullSafeNEQ(Binary, Predicate):
3051    pass
3052
3053
3054class Distance(Binary):
3055    pass
3056
3057
3058class Escape(Binary):
3059    pass
3060
3061
3062class Glob(Binary, Predicate):
3063    pass
3064
3065
3066class GT(Binary, Predicate):
3067    pass
3068
3069
3070class GTE(Binary, Predicate):
3071    pass
3072
3073
3074class ILike(Binary, Predicate):
3075    pass
3076
3077
3078class ILikeAny(Binary, Predicate):
3079    pass
3080
3081
3082class IntDiv(Binary):
3083    pass
3084
3085
3086class Is(Binary, Predicate):
3087    pass
3088
3089
3090class Kwarg(Binary):
3091    """Kwarg in special functions like func(kwarg => y)."""
3092
3093
3094class Like(Binary, Predicate):
3095    pass
3096
3097
3098class LikeAny(Binary, Predicate):
3099    pass
3100
3101
3102class LT(Binary, Predicate):
3103    pass
3104
3105
3106class LTE(Binary, Predicate):
3107    pass
3108
3109
3110class Mod(Binary):
3111    pass
3112
3113
3114class Mul(Binary):
3115    pass
3116
3117
3118class NEQ(Binary, Predicate):
3119    pass
3120
3121
3122class SimilarTo(Binary, Predicate):
3123    pass
3124
3125
3126class Slice(Binary):
3127    arg_types = {"this": False, "expression": False}
3128
3129
3130class Sub(Binary):
3131    pass
3132
3133
3134class ArrayOverlaps(Binary):
3135    pass
3136
3137
3138# Unary Expressions
3139# (NOT a)
3140class Unary(Expression):
3141    pass
3142
3143
3144class BitwiseNot(Unary):
3145    pass
3146
3147
3148class Not(Unary, Condition):
3149    pass
3150
3151
3152class Paren(Unary, Condition):
3153    arg_types = {"this": True, "with": False}
3154
3155
3156class Neg(Unary):
3157    pass
3158
3159
3160# Special Functions
3161class Alias(Expression):
3162    arg_types = {"this": True, "alias": False}
3163
3164    @property
3165    def output_name(self):
3166        return self.alias
3167
3168
3169class Aliases(Expression):
3170    arg_types = {"this": True, "expressions": True}
3171
3172    @property
3173    def aliases(self):
3174        return self.expressions
3175
3176
3177class AtTimeZone(Expression):
3178    arg_types = {"this": True, "zone": True}
3179
3180
3181class Between(Predicate):
3182    arg_types = {"this": True, "low": True, "high": True}
3183
3184
3185class Bracket(Condition):
3186    arg_types = {"this": True, "expressions": True}
3187
3188
3189class Distinct(Expression):
3190    arg_types = {"expressions": False, "on": False}
3191
3192
3193class In(Predicate):
3194    arg_types = {
3195        "this": True,
3196        "expressions": False,
3197        "query": False,
3198        "unnest": False,
3199        "field": False,
3200        "is_global": False,
3201    }
3202
3203
3204class TimeUnit(Expression):
3205    """Automatically converts unit arg into a var."""
3206
3207    arg_types = {"unit": False}
3208
3209    def __init__(self, **args):
3210        unit = args.get("unit")
3211        if isinstance(unit, (Column, Literal)):
3212            args["unit"] = Var(this=unit.name)
3213        elif isinstance(unit, Week):
3214            unit.set("this", Var(this=unit.this.name))
3215        super().__init__(**args)
3216
3217
3218class Interval(TimeUnit):
3219    arg_types = {"this": False, "unit": False}
3220
3221
3222class IgnoreNulls(Expression):
3223    pass
3224
3225
3226class RespectNulls(Expression):
3227    pass
3228
3229
3230# Functions
3231class Func(Condition):
3232    """
3233    The base class for all function expressions.
3234
3235    Attributes:
3236        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3237            treated as a variable length argument and the argument's value will be stored as a list.
3238        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3239            for this function expression. These values are used to map this node to a name during parsing
3240            as well as to provide the function's name during SQL string generation. By default the SQL
3241            name is set to the expression's class name transformed to snake case.
3242    """
3243
3244    is_var_len_args = False
3245
3246    @classmethod
3247    def from_arg_list(cls, args):
3248        if cls.is_var_len_args:
3249            all_arg_keys = list(cls.arg_types)
3250            # If this function supports variable length argument treat the last argument as such.
3251            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3252            num_non_var = len(non_var_len_arg_keys)
3253
3254            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3255            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3256        else:
3257            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3258
3259        return cls(**args_dict)
3260
3261    @classmethod
3262    def sql_names(cls):
3263        if cls is Func:
3264            raise NotImplementedError(
3265                "SQL name is only supported by concrete function implementations"
3266            )
3267        if "_sql_names" not in cls.__dict__:
3268            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3269        return cls._sql_names
3270
3271    @classmethod
3272    def sql_name(cls):
3273        return cls.sql_names()[0]
3274
3275    @classmethod
3276    def default_parser_mappings(cls):
3277        return {name: cls.from_arg_list for name in cls.sql_names()}
3278
3279
3280class AggFunc(Func):
3281    pass
3282
3283
3284class Abs(Func):
3285    pass
3286
3287
3288class Anonymous(Func):
3289    arg_types = {"this": True, "expressions": False}
3290    is_var_len_args = True
3291
3292
3293# https://docs.snowflake.com/en/sql-reference/functions/hll
3294# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3295class Hll(AggFunc):
3296    arg_types = {"this": True, "expressions": False}
3297    is_var_len_args = True
3298
3299
3300class ApproxDistinct(AggFunc):
3301    arg_types = {"this": True, "accuracy": False}
3302
3303
3304class Array(Func):
3305    arg_types = {"expressions": False}
3306    is_var_len_args = True
3307
3308
3309# https://docs.snowflake.com/en/sql-reference/functions/to_char
3310class ToChar(Func):
3311    arg_types = {"this": True, "format": False}
3312
3313
3314class GenerateSeries(Func):
3315    arg_types = {"start": True, "end": True, "step": False}
3316
3317
3318class ArrayAgg(AggFunc):
3319    pass
3320
3321
3322class ArrayAll(Func):
3323    arg_types = {"this": True, "expression": True}
3324
3325
3326class ArrayAny(Func):
3327    arg_types = {"this": True, "expression": True}
3328
3329
3330class ArrayConcat(Func):
3331    arg_types = {"this": True, "expressions": False}
3332    is_var_len_args = True
3333
3334
3335class ArrayContains(Binary, Func):
3336    pass
3337
3338
3339class ArrayContained(Binary):
3340    pass
3341
3342
3343class ArrayFilter(Func):
3344    arg_types = {"this": True, "expression": True}
3345    _sql_names = ["FILTER", "ARRAY_FILTER"]
3346
3347
3348class ArrayJoin(Func):
3349    arg_types = {"this": True, "expression": True, "null": False}
3350
3351
3352class ArraySize(Func):
3353    arg_types = {"this": True, "expression": False}
3354
3355
3356class ArraySort(Func):
3357    arg_types = {"this": True, "expression": False}
3358
3359
3360class ArraySum(Func):
3361    pass
3362
3363
3364class ArrayUnionAgg(AggFunc):
3365    pass
3366
3367
3368class Avg(AggFunc):
3369    pass
3370
3371
3372class AnyValue(AggFunc):
3373    pass
3374
3375
3376class Case(Func):
3377    arg_types = {"this": False, "ifs": True, "default": False}
3378
3379
3380class Cast(Func):
3381    arg_types = {"this": True, "to": True}
3382
3383    @property
3384    def name(self) -> str:
3385        return self.this.name
3386
3387    @property
3388    def to(self):
3389        return self.args["to"]
3390
3391    @property
3392    def output_name(self):
3393        return self.name
3394
3395    def is_type(self, dtype: DataType.Type) -> bool:
3396        return self.to.is_type(dtype)
3397
3398
3399class Collate(Binary):
3400    pass
3401
3402
3403class TryCast(Cast):
3404    pass
3405
3406
3407class Ceil(Func):
3408    arg_types = {"this": True, "decimals": False}
3409    _sql_names = ["CEIL", "CEILING"]
3410
3411
3412class Coalesce(Func):
3413    arg_types = {"this": True, "expressions": False}
3414    is_var_len_args = True
3415
3416
3417class Concat(Func):
3418    arg_types = {"expressions": True}
3419    is_var_len_args = True
3420
3421
3422class ConcatWs(Concat):
3423    _sql_names = ["CONCAT_WS"]
3424
3425
3426class Count(AggFunc):
3427    arg_types = {"this": False}
3428
3429
3430class CountIf(AggFunc):
3431    pass
3432
3433
3434class CurrentDate(Func):
3435    arg_types = {"this": False}
3436
3437
3438class CurrentDatetime(Func):
3439    arg_types = {"this": False}
3440
3441
3442class CurrentTime(Func):
3443    arg_types = {"this": False}
3444
3445
3446class CurrentTimestamp(Func):
3447    arg_types = {"this": False}
3448
3449
3450class DateAdd(Func, TimeUnit):
3451    arg_types = {"this": True, "expression": True, "unit": False}
3452
3453
3454class DateSub(Func, TimeUnit):
3455    arg_types = {"this": True, "expression": True, "unit": False}
3456
3457
3458class DateDiff(Func, TimeUnit):
3459    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3460    arg_types = {"this": True, "expression": True, "unit": False}
3461
3462
3463class DateTrunc(Func):
3464    arg_types = {"unit": True, "this": True, "zone": False}
3465
3466
3467class DatetimeAdd(Func, TimeUnit):
3468    arg_types = {"this": True, "expression": True, "unit": False}
3469
3470
3471class DatetimeSub(Func, TimeUnit):
3472    arg_types = {"this": True, "expression": True, "unit": False}
3473
3474
3475class DatetimeDiff(Func, TimeUnit):
3476    arg_types = {"this": True, "expression": True, "unit": False}
3477
3478
3479class DatetimeTrunc(Func, TimeUnit):
3480    arg_types = {"this": True, "unit": True, "zone": False}
3481
3482
3483class DayOfWeek(Func):
3484    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3485
3486
3487class DayOfMonth(Func):
3488    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3489
3490
3491class DayOfYear(Func):
3492    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3493
3494
3495class WeekOfYear(Func):
3496    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3497
3498
3499class LastDateOfMonth(Func):
3500    pass
3501
3502
3503class Extract(Func):
3504    arg_types = {"this": True, "expression": True}
3505
3506
3507class TimestampAdd(Func, TimeUnit):
3508    arg_types = {"this": True, "expression": True, "unit": False}
3509
3510
3511class TimestampSub(Func, TimeUnit):
3512    arg_types = {"this": True, "expression": True, "unit": False}
3513
3514
3515class TimestampDiff(Func, TimeUnit):
3516    arg_types = {"this": True, "expression": True, "unit": False}
3517
3518
3519class TimestampTrunc(Func, TimeUnit):
3520    arg_types = {"this": True, "unit": True, "zone": False}
3521
3522
3523class TimeAdd(Func, TimeUnit):
3524    arg_types = {"this": True, "expression": True, "unit": False}
3525
3526
3527class TimeSub(Func, TimeUnit):
3528    arg_types = {"this": True, "expression": True, "unit": False}
3529
3530
3531class TimeDiff(Func, TimeUnit):
3532    arg_types = {"this": True, "expression": True, "unit": False}
3533
3534
3535class TimeTrunc(Func, TimeUnit):
3536    arg_types = {"this": True, "unit": True, "zone": False}
3537
3538
3539class DateFromParts(Func):
3540    _sql_names = ["DATEFROMPARTS"]
3541    arg_types = {"year": True, "month": True, "day": True}
3542
3543
3544class DateStrToDate(Func):
3545    pass
3546
3547
3548class DateToDateStr(Func):
3549    pass
3550
3551
3552class DateToDi(Func):
3553    pass
3554
3555
3556class Day(Func):
3557    pass
3558
3559
3560class Decode(Func):
3561    arg_types = {"this": True, "charset": True, "replace": False}
3562
3563
3564class DiToDate(Func):
3565    pass
3566
3567
3568class Encode(Func):
3569    arg_types = {"this": True, "charset": True}
3570
3571
3572class Exp(Func):
3573    pass
3574
3575
3576class Explode(Func):
3577    pass
3578
3579
3580class ExponentialTimeDecayedAvg(AggFunc):
3581    arg_types = {"this": True, "time": False, "decay": False}
3582
3583
3584class Floor(Func):
3585    arg_types = {"this": True, "decimals": False}
3586
3587
3588class Greatest(Func):
3589    arg_types = {"this": True, "expressions": False}
3590    is_var_len_args = True
3591
3592
3593class GroupConcat(Func):
3594    arg_types = {"this": True, "separator": False}
3595
3596
3597class GroupUniqArray(AggFunc):
3598    arg_types = {"this": True, "size": False}
3599
3600
3601class Hex(Func):
3602    pass
3603
3604
3605class Histogram(AggFunc):
3606    arg_types = {"this": True, "bins": False}
3607
3608
3609class If(Func):
3610    arg_types = {"this": True, "true": True, "false": False}
3611
3612
3613class IfNull(Func):
3614    arg_types = {"this": True, "expression": False}
3615    _sql_names = ["IFNULL", "NVL"]
3616
3617
3618class Initcap(Func):
3619    pass
3620
3621
3622class JSONKeyValue(Expression):
3623    arg_types = {"this": True, "expression": True}
3624
3625
3626class JSONObject(Func):
3627    arg_types = {
3628        "expressions": False,
3629        "null_handling": False,
3630        "unique_keys": False,
3631        "return_type": False,
3632        "format_json": False,
3633        "encoding": False,
3634    }
3635
3636
3637class JSONBContains(Binary):
3638    _sql_names = ["JSONB_CONTAINS"]
3639
3640
3641class JSONExtract(Binary, Func):
3642    _sql_names = ["JSON_EXTRACT"]
3643
3644
3645class JSONExtractScalar(JSONExtract):
3646    _sql_names = ["JSON_EXTRACT_SCALAR"]
3647
3648
3649class JSONBExtract(JSONExtract):
3650    _sql_names = ["JSONB_EXTRACT"]
3651
3652
3653class JSONBExtractScalar(JSONExtract):
3654    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3655
3656
3657class JSONFormat(Func):
3658    arg_types = {"this": False, "options": False}
3659    _sql_names = ["JSON_FORMAT"]
3660
3661
3662class Least(Func):
3663    arg_types = {"expressions": False}
3664    is_var_len_args = True
3665
3666
3667class Length(Func):
3668    pass
3669
3670
3671class Levenshtein(Func):
3672    arg_types = {
3673        "this": True,
3674        "expression": False,
3675        "ins_cost": False,
3676        "del_cost": False,
3677        "sub_cost": False,
3678    }
3679
3680
3681class Ln(Func):
3682    pass
3683
3684
3685class Log(Func):
3686    arg_types = {"this": True, "expression": False}
3687
3688
3689class Log2(Func):
3690    pass
3691
3692
3693class Log10(Func):
3694    pass
3695
3696
3697class LogicalOr(AggFunc):
3698    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3699
3700
3701class LogicalAnd(AggFunc):
3702    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3703
3704
3705class Lower(Func):
3706    _sql_names = ["LOWER", "LCASE"]
3707
3708
3709class Map(Func):
3710    arg_types = {"keys": False, "values": False}
3711
3712
3713class VarMap(Func):
3714    arg_types = {"keys": True, "values": True}
3715    is_var_len_args = True
3716
3717
3718# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
3719class MatchAgainst(Func):
3720    arg_types = {"this": True, "expressions": True, "modifier": False}
3721
3722
3723class Max(AggFunc):
3724    arg_types = {"this": True, "expressions": False}
3725    is_var_len_args = True
3726
3727
3728class Min(AggFunc):
3729    arg_types = {"this": True, "expressions": False}
3730    is_var_len_args = True
3731
3732
3733class Month(Func):
3734    pass
3735
3736
3737class Nvl2(Func):
3738    arg_types = {"this": True, "true": True, "false": False}
3739
3740
3741class Posexplode(Func):
3742    pass
3743
3744
3745class Pow(Binary, Func):
3746    _sql_names = ["POWER", "POW"]
3747
3748
3749class PercentileCont(AggFunc):
3750    pass
3751
3752
3753class PercentileDisc(AggFunc):
3754    pass
3755
3756
3757class Quantile(AggFunc):
3758    arg_types = {"this": True, "quantile": True}
3759
3760
3761# Clickhouse-specific:
3762# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3763class Quantiles(AggFunc):
3764    arg_types = {"parameters": True, "expressions": True}
3765    is_var_len_args = True
3766
3767
3768class QuantileIf(AggFunc):
3769    arg_types = {"parameters": True, "expressions": True}
3770
3771
3772class ApproxQuantile(Quantile):
3773    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
3774
3775
3776class RangeN(Func):
3777    arg_types = {"this": True, "expressions": True, "each": False}
3778
3779
3780class ReadCSV(Func):
3781    _sql_names = ["READ_CSV"]
3782    is_var_len_args = True
3783    arg_types = {"this": True, "expressions": False}
3784
3785
3786class Reduce(Func):
3787    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
3788
3789
3790class RegexpExtract(Func):
3791    arg_types = {
3792        "this": True,
3793        "expression": True,
3794        "position": False,
3795        "occurrence": False,
3796        "group": False,
3797    }
3798
3799
3800class RegexpLike(Func):
3801    arg_types = {"this": True, "expression": True, "flag": False}
3802
3803
3804class RegexpILike(Func):
3805    arg_types = {"this": True, "expression": True, "flag": False}
3806
3807
3808# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
3809# limit is the number of times a pattern is applied
3810class RegexpSplit(Func):
3811    arg_types = {"this": True, "expression": True, "limit": False}
3812
3813
3814class Repeat(Func):
3815    arg_types = {"this": True, "times": True}
3816
3817
3818class Round(Func):
3819    arg_types = {"this": True, "decimals": False}
3820
3821
3822class RowNumber(Func):
3823    arg_types: t.Dict[str, t.Any] = {}
3824
3825
3826class SafeDivide(Func):
3827    arg_types = {"this": True, "expression": True}
3828
3829
3830class SetAgg(AggFunc):
3831    pass
3832
3833
3834class SortArray(Func):
3835    arg_types = {"this": True, "asc": False}
3836
3837
3838class Split(Func):
3839    arg_types = {"this": True, "expression": True, "limit": False}
3840
3841
3842# Start may be omitted in the case of postgres
3843# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
3844class Substring(Func):
3845    arg_types = {"this": True, "start": False, "length": False}
3846
3847
3848class StrPosition(Func):
3849    arg_types = {
3850        "this": True,
3851        "substr": True,
3852        "position": False,
3853        "instance": False,
3854    }
3855
3856
3857class StrToDate(Func):
3858    arg_types = {"this": True, "format": True}
3859
3860
3861class StrToTime(Func):
3862    arg_types = {"this": True, "format": True}
3863
3864
3865# Spark allows unix_timestamp()
3866# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
3867class StrToUnix(Func):
3868    arg_types = {"this": False, "format": False}
3869
3870
3871class NumberToStr(Func):
3872    arg_types = {"this": True, "format": True}
3873
3874
3875class Struct(Func):
3876    arg_types = {"expressions": True}
3877    is_var_len_args = True
3878
3879
3880class StructExtract(Func):
3881    arg_types = {"this": True, "expression": True}
3882
3883
3884class Sum(AggFunc):
3885    pass
3886
3887
3888class Sqrt(Func):
3889    pass
3890
3891
3892class Stddev(AggFunc):
3893    pass
3894
3895
3896class StddevPop(AggFunc):
3897    pass
3898
3899
3900class StddevSamp(AggFunc):
3901    pass
3902
3903
3904class TimeToStr(Func):
3905    arg_types = {"this": True, "format": True}
3906
3907
3908class TimeToTimeStr(Func):
3909    pass
3910
3911
3912class TimeToUnix(Func):
3913    pass
3914
3915
3916class TimeStrToDate(Func):
3917    pass
3918
3919
3920class TimeStrToTime(Func):
3921    pass
3922
3923
3924class TimeStrToUnix(Func):
3925    pass
3926
3927
3928class Trim(Func):
3929    arg_types = {
3930        "this": True,
3931        "expression": False,
3932        "position": False,
3933        "collation": False,
3934    }
3935
3936
3937class TsOrDsAdd(Func, TimeUnit):
3938    arg_types = {"this": True, "expression": True, "unit": False}
3939
3940
3941class TsOrDsToDateStr(Func):
3942    pass
3943
3944
3945class TsOrDsToDate(Func):
3946    arg_types = {"this": True, "format": False}
3947
3948
3949class TsOrDiToDi(Func):
3950    pass
3951
3952
3953class Unhex(Func):
3954    pass
3955
3956
3957class UnixToStr(Func):
3958    arg_types = {"this": True, "format": False}
3959
3960
3961# https://prestodb.io/docs/current/functions/datetime.html
3962# presto has weird zone/hours/minutes
3963class UnixToTime(Func):
3964    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3965
3966    SECONDS = Literal.string("seconds")
3967    MILLIS = Literal.string("millis")
3968    MICROS = Literal.string("micros")
3969
3970
3971class UnixToTimeStr(Func):
3972    pass
3973
3974
3975class Upper(Func):
3976    _sql_names = ["UPPER", "UCASE"]
3977
3978
3979class Variance(AggFunc):
3980    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
3981
3982
3983class VariancePop(AggFunc):
3984    _sql_names = ["VARIANCE_POP", "VAR_POP"]
3985
3986
3987class Week(Func):
3988    arg_types = {"this": True, "mode": False}
3989
3990
3991class XMLTable(Func):
3992    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
3993
3994
3995class Year(Func):
3996    pass
3997
3998
3999class Use(Expression):
4000    arg_types = {"this": True, "kind": False}
4001
4002
4003class Merge(Expression):
4004    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4005
4006
4007class When(Func):
4008    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4009
4010
4011def _norm_arg(arg):
4012    return arg.lower() if type(arg) is str else arg
4013
4014
4015ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4016
4017
4018# Helpers
4019def maybe_parse(
4020    sql_or_expression: ExpOrStr,
4021    *,
4022    into: t.Optional[IntoType] = None,
4023    dialect: DialectType = None,
4024    prefix: t.Optional[str] = None,
4025    copy: bool = False,
4026    **opts,
4027) -> Expression:
4028    """Gracefully handle a possible string or expression.
4029
4030    Example:
4031        >>> maybe_parse("1")
4032        (LITERAL this: 1, is_string: False)
4033        >>> maybe_parse(to_identifier("x"))
4034        (IDENTIFIER this: x, quoted: False)
4035
4036    Args:
4037        sql_or_expression: the SQL code string or an expression
4038        into: the SQLGlot Expression to parse into
4039        dialect: the dialect used to parse the input expressions (in the case that an
4040            input expression is a SQL string).
4041        prefix: a string to prefix the sql with before it gets parsed
4042            (automatically includes a space)
4043        copy: whether or not to copy the expression.
4044        **opts: other options to use to parse the input expressions (again, in the case
4045            that an input expression is a SQL string).
4046
4047    Returns:
4048        Expression: the parsed or given expression.
4049    """
4050    if isinstance(sql_or_expression, Expression):
4051        if copy:
4052            return sql_or_expression.copy()
4053        return sql_or_expression
4054
4055    import sqlglot
4056
4057    sql = str(sql_or_expression)
4058    if prefix:
4059        sql = f"{prefix} {sql}"
4060    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4061
4062
4063def _maybe_copy(instance, copy=True):
4064    return instance.copy() if copy else instance
4065
4066
4067def _is_wrong_expression(expression, into):
4068    return isinstance(expression, Expression) and not isinstance(expression, into)
4069
4070
4071def _apply_builder(
4072    expression,
4073    instance,
4074    arg,
4075    copy=True,
4076    prefix=None,
4077    into=None,
4078    dialect=None,
4079    **opts,
4080):
4081    if _is_wrong_expression(expression, into):
4082        expression = into(this=expression)
4083    instance = _maybe_copy(instance, copy)
4084    expression = maybe_parse(
4085        sql_or_expression=expression,
4086        prefix=prefix,
4087        into=into,
4088        dialect=dialect,
4089        **opts,
4090    )
4091    instance.set(arg, expression)
4092    return instance
4093
4094
4095def _apply_child_list_builder(
4096    *expressions,
4097    instance,
4098    arg,
4099    append=True,
4100    copy=True,
4101    prefix=None,
4102    into=None,
4103    dialect=None,
4104    properties=None,
4105    **opts,
4106):
4107    instance = _maybe_copy(instance, copy)
4108    parsed = []
4109    for expression in expressions:
4110        if _is_wrong_expression(expression, into):
4111            expression = into(expressions=[expression])
4112        expression = maybe_parse(
4113            expression,
4114            into=into,
4115            dialect=dialect,
4116            prefix=prefix,
4117            **opts,
4118        )
4119        parsed.extend(expression.expressions)
4120
4121    existing = instance.args.get(arg)
4122    if append and existing:
4123        parsed = existing.expressions + parsed
4124
4125    child = into(expressions=parsed)
4126    for k, v in (properties or {}).items():
4127        child.set(k, v)
4128    instance.set(arg, child)
4129    return instance
4130
4131
4132def _apply_list_builder(
4133    *expressions,
4134    instance,
4135    arg,
4136    append=True,
4137    copy=True,
4138    prefix=None,
4139    into=None,
4140    dialect=None,
4141    **opts,
4142):
4143    inst = _maybe_copy(instance, copy)
4144
4145    expressions = [
4146        maybe_parse(
4147            sql_or_expression=expression,
4148            into=into,
4149            prefix=prefix,
4150            dialect=dialect,
4151            **opts,
4152        )
4153        for expression in expressions
4154    ]
4155
4156    existing_expressions = inst.args.get(arg)
4157    if append and existing_expressions:
4158        expressions = existing_expressions + expressions
4159
4160    inst.set(arg, expressions)
4161    return inst
4162
4163
4164def _apply_conjunction_builder(
4165    *expressions,
4166    instance,
4167    arg,
4168    into=None,
4169    append=True,
4170    copy=True,
4171    dialect=None,
4172    **opts,
4173):
4174    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4175    if not expressions:
4176        return instance
4177
4178    inst = _maybe_copy(instance, copy)
4179
4180    existing = inst.args.get(arg)
4181    if append and existing is not None:
4182        expressions = [existing.this if into else existing] + list(expressions)
4183
4184    node = and_(*expressions, dialect=dialect, **opts)
4185
4186    inst.set(arg, into(this=node) if into else node)
4187    return inst
4188
4189
4190def _combine(expressions, operator, dialect=None, **opts):
4191    expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions]
4192    this = expressions[0]
4193    if expressions[1:]:
4194        this = _wrap_operator(this)
4195    for expression in expressions[1:]:
4196        this = operator(this=this, expression=_wrap_operator(expression))
4197    return this
4198
4199
4200def _wrap_operator(expression):
4201    if isinstance(expression, (And, Or, Not)):
4202        expression = Paren(this=expression)
4203    return expression
4204
4205
4206def union(left, right, distinct=True, dialect=None, **opts):
4207    """
4208    Initializes a syntax tree from one UNION expression.
4209
4210    Example:
4211        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4212        'SELECT * FROM foo UNION SELECT * FROM bla'
4213
4214    Args:
4215        left (str | Expression): the SQL code string corresponding to the left-hand side.
4216            If an `Expression` instance is passed, it will be used as-is.
4217        right (str | Expression): the SQL code string corresponding to the right-hand side.
4218            If an `Expression` instance is passed, it will be used as-is.
4219        distinct (bool): set the DISTINCT flag if and only if this is true.
4220        dialect (str): the dialect used to parse the input expression.
4221        opts (kwargs): other options to use to parse the input expressions.
4222    Returns:
4223        Union: the syntax tree for the UNION expression.
4224    """
4225    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4226    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4227
4228    return Union(this=left, expression=right, distinct=distinct)
4229
4230
4231def intersect(left, right, distinct=True, dialect=None, **opts):
4232    """
4233    Initializes a syntax tree from one INTERSECT expression.
4234
4235    Example:
4236        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4237        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4238
4239    Args:
4240        left (str | Expression): the SQL code string corresponding to the left-hand side.
4241            If an `Expression` instance is passed, it will be used as-is.
4242        right (str | Expression): the SQL code string corresponding to the right-hand side.
4243            If an `Expression` instance is passed, it will be used as-is.
4244        distinct (bool): set the DISTINCT flag if and only if this is true.
4245        dialect (str): the dialect used to parse the input expression.
4246        opts (kwargs): other options to use to parse the input expressions.
4247    Returns:
4248        Intersect: the syntax tree for the INTERSECT expression.
4249    """
4250    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4251    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4252
4253    return Intersect(this=left, expression=right, distinct=distinct)
4254
4255
4256def except_(left, right, distinct=True, dialect=None, **opts):
4257    """
4258    Initializes a syntax tree from one EXCEPT expression.
4259
4260    Example:
4261        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4262        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4263
4264    Args:
4265        left (str | Expression): the SQL code string corresponding to the left-hand side.
4266            If an `Expression` instance is passed, it will be used as-is.
4267        right (str | Expression): the SQL code string corresponding to the right-hand side.
4268            If an `Expression` instance is passed, it will be used as-is.
4269        distinct (bool): set the DISTINCT flag if and only if this is true.
4270        dialect (str): the dialect used to parse the input expression.
4271        opts (kwargs): other options to use to parse the input expressions.
4272    Returns:
4273        Except: the syntax tree for the EXCEPT statement.
4274    """
4275    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4276    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4277
4278    return Except(this=left, expression=right, distinct=distinct)
4279
4280
4281def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4282    """
4283    Initializes a syntax tree from one or multiple SELECT expressions.
4284
4285    Example:
4286        >>> select("col1", "col2").from_("tbl").sql()
4287        'SELECT col1, col2 FROM tbl'
4288
4289    Args:
4290        *expressions: the SQL code string to parse as the expressions of a
4291            SELECT statement. If an Expression instance is passed, this is used as-is.
4292        dialect: the dialect used to parse the input expressions (in the case that an
4293            input expression is a SQL string).
4294        **opts: other options to use to parse the input expressions (again, in the case
4295            that an input expression is a SQL string).
4296
4297    Returns:
4298        Select: the syntax tree for the SELECT statement.
4299    """
4300    return Select().select(*expressions, dialect=dialect, **opts)
4301
4302
4303def from_(*expressions, dialect=None, **opts) -> Select:
4304    """
4305    Initializes a syntax tree from a FROM expression.
4306
4307    Example:
4308        >>> from_("tbl").select("col1", "col2").sql()
4309        'SELECT col1, col2 FROM tbl'
4310
4311    Args:
4312        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4313            SELECT statement. If an Expression instance is passed, this is used as-is.
4314        dialect (str): the dialect used to parse the input expression (in the case that the
4315            input expression is a SQL string).
4316        **opts: other options to use to parse the input expressions (again, in the case
4317            that the input expression is a SQL string).
4318
4319    Returns:
4320        Select: the syntax tree for the SELECT statement.
4321    """
4322    return Select().from_(*expressions, dialect=dialect, **opts)
4323
4324
4325def update(
4326    table: str | Table,
4327    properties: dict,
4328    where: t.Optional[ExpOrStr] = None,
4329    from_: t.Optional[ExpOrStr] = None,
4330    dialect: DialectType = None,
4331    **opts,
4332) -> Update:
4333    """
4334    Creates an update statement.
4335
4336    Example:
4337        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4338        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4339
4340    Args:
4341        *properties: dictionary of properties to set which are
4342            auto converted to sql objects eg None -> NULL
4343        where: sql conditional parsed into a WHERE statement
4344        from_: sql statement parsed into a FROM statement
4345        dialect: the dialect used to parse the input expressions.
4346        **opts: other options to use to parse the input expressions.
4347
4348    Returns:
4349        Update: the syntax tree for the UPDATE statement.
4350    """
4351    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4352    update_expr.set(
4353        "expressions",
4354        [
4355            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4356            for k, v in properties.items()
4357        ],
4358    )
4359    if from_:
4360        update_expr.set(
4361            "from",
4362            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4363        )
4364    if isinstance(where, Condition):
4365        where = Where(this=where)
4366    if where:
4367        update_expr.set(
4368            "where",
4369            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4370        )
4371    return update_expr
4372
4373
4374def delete(
4375    table: ExpOrStr,
4376    where: t.Optional[ExpOrStr] = None,
4377    returning: t.Optional[ExpOrStr] = None,
4378    dialect: DialectType = None,
4379    **opts,
4380) -> Delete:
4381    """
4382    Builds a delete statement.
4383
4384    Example:
4385        >>> delete("my_table", where="id > 1").sql()
4386        'DELETE FROM my_table WHERE id > 1'
4387
4388    Args:
4389        where: sql conditional parsed into a WHERE statement
4390        returning: sql conditional parsed into a RETURNING statement
4391        dialect: the dialect used to parse the input expressions.
4392        **opts: other options to use to parse the input expressions.
4393
4394    Returns:
4395        Delete: the syntax tree for the DELETE statement.
4396    """
4397    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4398    if where:
4399        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4400    if returning:
4401        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4402    return delete_expr
4403
4404
4405def condition(expression, dialect=None, **opts) -> Condition:
4406    """
4407    Initialize a logical condition expression.
4408
4409    Example:
4410        >>> condition("x=1").sql()
4411        'x = 1'
4412
4413        This is helpful for composing larger logical syntax trees:
4414        >>> where = condition("x=1")
4415        >>> where = where.and_("y=1")
4416        >>> Select().from_("tbl").select("*").where(where).sql()
4417        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4418
4419    Args:
4420        *expression (str | Expression): the SQL code string to parse.
4421            If an Expression instance is passed, this is used as-is.
4422        dialect (str): the dialect used to parse the input expression (in the case that the
4423            input expression is a SQL string).
4424        **opts: other options to use to parse the input expressions (again, in the case
4425            that the input expression is a SQL string).
4426
4427    Returns:
4428        Condition: the expression
4429    """
4430    return maybe_parse(  # type: ignore
4431        expression,
4432        into=Condition,
4433        dialect=dialect,
4434        **opts,
4435    )
4436
4437
4438def and_(*expressions, dialect=None, **opts) -> And:
4439    """
4440    Combine multiple conditions with an AND logical operator.
4441
4442    Example:
4443        >>> and_("x=1", and_("y=1", "z=1")).sql()
4444        'x = 1 AND (y = 1 AND z = 1)'
4445
4446    Args:
4447        *expressions (str | Expression): the SQL code strings to parse.
4448            If an Expression instance is passed, this is used as-is.
4449        dialect (str): the dialect used to parse the input expression.
4450        **opts: other options to use to parse the input expressions.
4451
4452    Returns:
4453        And: the new condition
4454    """
4455    return _combine(expressions, And, dialect, **opts)
4456
4457
4458def or_(*expressions, dialect=None, **opts) -> Or:
4459    """
4460    Combine multiple conditions with an OR logical operator.
4461
4462    Example:
4463        >>> or_("x=1", or_("y=1", "z=1")).sql()
4464        'x = 1 OR (y = 1 OR z = 1)'
4465
4466    Args:
4467        *expressions (str | Expression): the SQL code strings to parse.
4468            If an Expression instance is passed, this is used as-is.
4469        dialect (str): the dialect used to parse the input expression.
4470        **opts: other options to use to parse the input expressions.
4471
4472    Returns:
4473        Or: the new condition
4474    """
4475    return _combine(expressions, Or, dialect, **opts)
4476
4477
4478def not_(expression, dialect=None, **opts) -> Not:
4479    """
4480    Wrap a condition with a NOT operator.
4481
4482    Example:
4483        >>> not_("this_suit='black'").sql()
4484        "NOT this_suit = 'black'"
4485
4486    Args:
4487        expression (str | Expression): the SQL code strings to parse.
4488            If an Expression instance is passed, this is used as-is.
4489        dialect (str): the dialect used to parse the input expression.
4490        **opts: other options to use to parse the input expressions.
4491
4492    Returns:
4493        Not: the new condition
4494    """
4495    this = condition(
4496        expression,
4497        dialect=dialect,
4498        **opts,
4499    )
4500    return Not(this=_wrap_operator(this))
4501
4502
4503def paren(expression) -> Paren:
4504    return Paren(this=expression)
4505
4506
4507SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4508
4509
4510@t.overload
4511def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4512    ...
4513
4514
4515@t.overload
4516def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4517    ...
4518
4519
4520def to_identifier(name, quoted=None):
4521    """Builds an identifier.
4522
4523    Args:
4524        name: The name to turn into an identifier.
4525        quoted: Whether or not force quote the identifier.
4526
4527    Returns:
4528        The identifier ast node.
4529    """
4530
4531    if name is None:
4532        return None
4533
4534    if isinstance(name, Identifier):
4535        identifier = name
4536    elif isinstance(name, str):
4537        identifier = Identifier(
4538            this=name,
4539            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4540        )
4541    else:
4542        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4543    return identifier
4544
4545
4546INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4547
4548
4549def to_interval(interval: str | Literal) -> Interval:
4550    """Builds an interval expression from a string like '1 day' or '5 months'."""
4551    if isinstance(interval, Literal):
4552        if not interval.is_string:
4553            raise ValueError("Invalid interval string.")
4554
4555        interval = interval.this
4556
4557    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4558
4559    if not interval_parts:
4560        raise ValueError("Invalid interval string.")
4561
4562    return Interval(
4563        this=Literal.string(interval_parts.group(1)),
4564        unit=Var(this=interval_parts.group(2)),
4565    )
4566
4567
4568@t.overload
4569def to_table(sql_path: str | Table, **kwargs) -> Table:
4570    ...
4571
4572
4573@t.overload
4574def to_table(sql_path: None, **kwargs) -> None:
4575    ...
4576
4577
4578def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4579    """
4580    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4581    If a table is passed in then that table is returned.
4582
4583    Args:
4584        sql_path: a `[catalog].[schema].[table]` string.
4585
4586    Returns:
4587        A table expression.
4588    """
4589    if sql_path is None or isinstance(sql_path, Table):
4590        return sql_path
4591    if not isinstance(sql_path, str):
4592        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4593
4594    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4595    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4596
4597
4598def to_column(sql_path: str | Column, **kwargs) -> Column:
4599    """
4600    Create a column from a `[table].[column]` sql path. Schema is optional.
4601
4602    If a column is passed in then that column is returned.
4603
4604    Args:
4605        sql_path: `[table].[column]` string
4606    Returns:
4607        Table: A column expression
4608    """
4609    if sql_path is None or isinstance(sql_path, Column):
4610        return sql_path
4611    if not isinstance(sql_path, str):
4612        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4613    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4614
4615
4616def alias_(
4617    expression: ExpOrStr,
4618    alias: str | Identifier,
4619    table: bool | t.Sequence[str | Identifier] = False,
4620    quoted: t.Optional[bool] = None,
4621    dialect: DialectType = None,
4622    **opts,
4623):
4624    """Create an Alias expression.
4625
4626    Example:
4627        >>> alias_('foo', 'bar').sql()
4628        'foo AS bar'
4629
4630        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4631        '(SELECT 1, 2) AS bar(a, b)'
4632
4633    Args:
4634        expression: the SQL code strings to parse.
4635            If an Expression instance is passed, this is used as-is.
4636        alias: the alias name to use. If the name has
4637            special characters it is quoted.
4638        table: Whether or not to create a table alias, can also be a list of columns.
4639        quoted: whether or not to quote the alias
4640        dialect: the dialect used to parse the input expression.
4641        **opts: other options to use to parse the input expressions.
4642
4643    Returns:
4644        Alias: the aliased expression
4645    """
4646    exp = maybe_parse(expression, dialect=dialect, **opts)
4647    alias = to_identifier(alias, quoted=quoted)
4648
4649    if table:
4650        table_alias = TableAlias(this=alias)
4651        exp.set("alias", table_alias)
4652
4653        if not isinstance(table, bool):
4654            for column in table:
4655                table_alias.append("columns", to_identifier(column, quoted=quoted))
4656
4657        return exp
4658
4659    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4660    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4661    # for the complete Window expression.
4662    #
4663    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4664
4665    if "alias" in exp.arg_types and not isinstance(exp, Window):
4666        exp = exp.copy()
4667        exp.set("alias", alias)
4668        return exp
4669    return Alias(this=exp, alias=alias)
4670
4671
4672def subquery(expression, alias=None, dialect=None, **opts):
4673    """
4674    Build a subquery expression.
4675
4676    Example:
4677        >>> subquery('select x from tbl', 'bar').select('x').sql()
4678        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4679
4680    Args:
4681        expression (str | Expression): the SQL code strings to parse.
4682            If an Expression instance is passed, this is used as-is.
4683        alias (str | Expression): the alias name to use.
4684        dialect (str): the dialect used to parse the input expression.
4685        **opts: other options to use to parse the input expressions.
4686
4687    Returns:
4688        Select: a new select with the subquery expression included
4689    """
4690
4691    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4692    return Select().from_(expression, dialect=dialect, **opts)
4693
4694
4695def column(
4696    col: str | Identifier,
4697    table: t.Optional[str | Identifier] = None,
4698    db: t.Optional[str | Identifier] = None,
4699    catalog: t.Optional[str | Identifier] = None,
4700    quoted: t.Optional[bool] = None,
4701) -> Column:
4702    """
4703    Build a Column.
4704
4705    Args:
4706        col: column name
4707        table: table name
4708        db: db name
4709        catalog: catalog name
4710        quoted: whether or not to force quote each part
4711    Returns:
4712        Column: column instance
4713    """
4714    return Column(
4715        this=to_identifier(col, quoted=quoted),
4716        table=to_identifier(table, quoted=quoted),
4717        db=to_identifier(db, quoted=quoted),
4718        catalog=to_identifier(catalog, quoted=quoted),
4719    )
4720
4721
4722def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4723    """Cast an expression to a data type.
4724
4725    Example:
4726        >>> cast('x + 1', 'int').sql()
4727        'CAST(x + 1 AS INT)'
4728
4729    Args:
4730        expression: The expression to cast.
4731        to: The datatype to cast to.
4732
4733    Returns:
4734        A cast node.
4735    """
4736    expression = maybe_parse(expression, **opts)
4737    return Cast(this=expression, to=DataType.build(to, **opts))
4738
4739
4740def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4741    """Build a Table.
4742
4743    Args:
4744        table (str | Expression): column name
4745        db (str | Expression): db name
4746        catalog (str | Expression): catalog name
4747
4748    Returns:
4749        Table: table instance
4750    """
4751    return Table(
4752        this=to_identifier(table, quoted=quoted),
4753        db=to_identifier(db, quoted=quoted),
4754        catalog=to_identifier(catalog, quoted=quoted),
4755        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4756    )
4757
4758
4759def values(
4760    values: t.Iterable[t.Tuple[t.Any, ...]],
4761    alias: t.Optional[str] = None,
4762    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4763) -> Values:
4764    """Build VALUES statement.
4765
4766    Example:
4767        >>> values([(1, '2')]).sql()
4768        "VALUES (1, '2')"
4769
4770    Args:
4771        values: values statements that will be converted to SQL
4772        alias: optional alias
4773        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4774         If either are provided then an alias is also required.
4775         If a dictionary is provided then the first column of the values will be casted to the expected type
4776         in order to help with type inference.
4777
4778    Returns:
4779        Values: the Values expression object
4780    """
4781    if columns and not alias:
4782        raise ValueError("Alias is required when providing columns")
4783    table_alias = (
4784        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4785        if columns
4786        else TableAlias(this=to_identifier(alias) if alias else None)
4787    )
4788    expressions = [convert(tup) for tup in values]
4789    if columns and isinstance(columns, dict):
4790        types = list(columns.values())
4791        expressions[0].set(
4792            "expressions",
4793            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4794        )
4795    return Values(
4796        expressions=expressions,
4797        alias=table_alias,
4798    )
4799
4800
4801def var(name: t.Optional[ExpOrStr]) -> Var:
4802    """Build a SQL variable.
4803
4804    Example:
4805        >>> repr(var('x'))
4806        '(VAR this: x)'
4807
4808        >>> repr(var(column('x', table='y')))
4809        '(VAR this: x)'
4810
4811    Args:
4812        name: The name of the var or an expression who's name will become the var.
4813
4814    Returns:
4815        The new variable node.
4816    """
4817    if not name:
4818        raise ValueError("Cannot convert empty name into var.")
4819
4820    if isinstance(name, Expression):
4821        name = name.name
4822    return Var(this=name)
4823
4824
4825def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4826    """Build ALTER TABLE... RENAME... expression
4827
4828    Args:
4829        old_name: The old name of the table
4830        new_name: The new name of the table
4831
4832    Returns:
4833        Alter table expression
4834    """
4835    old_table = to_table(old_name)
4836    new_table = to_table(new_name)
4837    return AlterTable(
4838        this=old_table,
4839        actions=[
4840            RenameTable(this=new_table),
4841        ],
4842    )
4843
4844
4845def convert(value) -> Expression:
4846    """Convert a python value into an expression object.
4847
4848    Raises an error if a conversion is not possible.
4849
4850    Args:
4851        value (Any): a python object
4852
4853    Returns:
4854        Expression: the equivalent expression object
4855    """
4856    if isinstance(value, Expression):
4857        return value
4858    if value is None:
4859        return NULL
4860    if isinstance(value, bool):
4861        return Boolean(this=value)
4862    if isinstance(value, str):
4863        return Literal.string(value)
4864    if isinstance(value, float) and math.isnan(value):
4865        return NULL
4866    if isinstance(value, numbers.Number):
4867        return Literal.number(value)
4868    if isinstance(value, tuple):
4869        return Tuple(expressions=[convert(v) for v in value])
4870    if isinstance(value, list):
4871        return Array(expressions=[convert(v) for v in value])
4872    if isinstance(value, dict):
4873        return Map(
4874            keys=[convert(k) for k in value],
4875            values=[convert(v) for v in value.values()],
4876        )
4877    if isinstance(value, datetime.datetime):
4878        datetime_literal = Literal.string(
4879            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4880        )
4881        return TimeStrToTime(this=datetime_literal)
4882    if isinstance(value, datetime.date):
4883        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4884        return DateStrToDate(this=date_literal)
4885    raise ValueError(f"Cannot convert {value}")
4886
4887
4888def replace_children(expression, fun, *args, **kwargs):
4889    """
4890    Replace children of an expression with the result of a lambda fun(child) -> exp.
4891    """
4892    for k, v in expression.args.items():
4893        is_list_arg = type(v) is list
4894
4895        child_nodes = v if is_list_arg else [v]
4896        new_child_nodes = []
4897
4898        for cn in child_nodes:
4899            if isinstance(cn, Expression):
4900                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4901                    new_child_nodes.append(child_node)
4902                    child_node.parent = expression
4903                    child_node.arg_key = k
4904            else:
4905                new_child_nodes.append(cn)
4906
4907        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
4908
4909
4910def column_table_names(expression):
4911    """
4912    Return all table names referenced through columns in an expression.
4913
4914    Example:
4915        >>> import sqlglot
4916        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4917        ['c', 'a']
4918
4919    Args:
4920        expression (sqlglot.Expression): expression to find table names
4921
4922    Returns:
4923        list: A list of unique names
4924    """
4925    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
4926
4927
4928def table_name(table) -> str:
4929    """Get the full name of a table as a string.
4930
4931    Args:
4932        table (exp.Table | str): table expression node or string.
4933
4934    Examples:
4935        >>> from sqlglot import exp, parse_one
4936        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4937        'a.b.c'
4938
4939    Returns:
4940        The table name.
4941    """
4942
4943    table = maybe_parse(table, into=Table)
4944
4945    if not table:
4946        raise ValueError(f"Cannot parse {table}")
4947
4948    return ".".join(
4949        part
4950        for part in (
4951            table.text("catalog"),
4952            table.text("db"),
4953            table.name,
4954        )
4955        if part
4956    )
4957
4958
4959def replace_tables(expression, mapping):
4960    """Replace all tables in expression according to the mapping.
4961
4962    Args:
4963        expression (sqlglot.Expression): expression node to be transformed and replaced.
4964        mapping (Dict[str, str]): mapping of table names.
4965
4966    Examples:
4967        >>> from sqlglot import exp, parse_one
4968        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4969        'SELECT * FROM c'
4970
4971    Returns:
4972        The mapped expression.
4973    """
4974
4975    def _replace_tables(node):
4976        if isinstance(node, Table):
4977            new_name = mapping.get(table_name(node))
4978            if new_name:
4979                return to_table(
4980                    new_name,
4981                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4982                )
4983        return node
4984
4985    return expression.transform(_replace_tables)
4986
4987
4988def replace_placeholders(expression, *args, **kwargs):
4989    """Replace placeholders in an expression.
4990
4991    Args:
4992        expression (sqlglot.Expression): expression node to be transformed and replaced.
4993        args: positional names that will substitute unnamed placeholders in the given order.
4994        kwargs: keyword arguments that will substitute named placeholders.
4995
4996    Examples:
4997        >>> from sqlglot import exp, parse_one
4998        >>> replace_placeholders(
4999        ...     parse_one("select * from :tbl where ? = ?"),
5000        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5001        ... ).sql()
5002        "SELECT * FROM foo WHERE str_col = 'b'"
5003
5004    Returns:
5005        The mapped expression.
5006    """
5007
5008    def _replace_placeholders(node, args, **kwargs):
5009        if isinstance(node, Placeholder):
5010            if node.name:
5011                new_name = kwargs.get(node.name)
5012                if new_name:
5013                    return convert(new_name)
5014            else:
5015                try:
5016                    return convert(next(args))
5017                except StopIteration:
5018                    pass
5019        return node
5020
5021    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5022
5023
5024def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5025    """Transforms an expression by expanding all referenced sources into subqueries.
5026
5027    Examples:
5028        >>> from sqlglot import parse_one
5029        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5030        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5031
5032    Args:
5033        expression: The expression to expand.
5034        sources: A dictionary of name to Subqueryables.
5035        copy: Whether or not to copy the expression during transformation. Defaults to True.
5036
5037    Returns:
5038        The transformed expression.
5039    """
5040
5041    def _expand(node: Expression):
5042        if isinstance(node, Table):
5043            name = table_name(node)
5044            source = sources.get(name)
5045            if source:
5046                subquery = source.subquery(node.alias or name)
5047                subquery.comments = [f"source: {name}"]
5048                return subquery
5049        return node
5050
5051    return expression.transform(_expand, copy=copy)
5052
5053
5054def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5055    """
5056    Returns a Func expression.
5057
5058    Examples:
5059        >>> func("abs", 5).sql()
5060        'ABS(5)'
5061
5062        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5063        'CAST(5 AS DOUBLE)'
5064
5065    Args:
5066        name: the name of the function to build.
5067        args: the args used to instantiate the function of interest.
5068        dialect: the source dialect.
5069        kwargs: the kwargs used to instantiate the function of interest.
5070
5071    Note:
5072        The arguments `args` and `kwargs` are mutually exclusive.
5073
5074    Returns:
5075        An instance of the function of interest, or an anonymous function, if `name` doesn't
5076        correspond to an existing `sqlglot.expressions.Func` class.
5077    """
5078    if args and kwargs:
5079        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5080
5081    from sqlglot.dialects.dialect import Dialect
5082
5083    converted = [convert(arg) for arg in args]
5084    kwargs = {key: convert(value) for key, value in kwargs.items()}
5085
5086    parser = Dialect.get_or_raise(dialect)().parser()
5087    from_args_list = parser.FUNCTIONS.get(name.upper())
5088
5089    if from_args_list:
5090        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5091    else:
5092        kwargs = kwargs or {"expressions": converted}
5093        function = Anonymous(this=name, **kwargs)
5094
5095    for error_message in function.error_messages(converted):
5096        raise ValueError(error_message)
5097
5098    return function
5099
5100
5101def true():
5102    """
5103    Returns a true Boolean expression.
5104    """
5105    return Boolean(this=True)
5106
5107
5108def false():
5109    """
5110    Returns a false Boolean expression.
5111    """
5112    return Boolean(this=False)
5113
5114
5115def null():
5116    """
5117    Returns a Null expression.
5118    """
5119    return Null()
5120
5121
5122# TODO: deprecate this
5123TRUE = Boolean(this=True)
5124FALSE = Boolean(this=False)
5125NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68
 69    Example:
 70        >>> class Foo(Expression):
 71        ...     arg_types = {"this": True, "expression": False}
 72
 73        The above definition informs us that Foo is an Expression that requires an argument called
 74        "this" and may also optionally receive an argument called "expression".
 75
 76    Args:
 77        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 78        parent: a reference to the parent expression (or None, in case of root expressions).
 79        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 80            uses to refer to it.
 81        comments: a list of comments that are associated with a given expression. This is used in
 82            order to preserve comments when transpiling SQL code.
 83        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 84            optimizer, in order to enable some transformations that require type information.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)
274
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)
285
286    def _set_parent(self, arg_key, value):
287        if hasattr(value, "parent"):
288            value.parent = self
289            value.arg_key = arg_key
290        elif type(value) is list:
291            for v in value:
292                if hasattr(v, "parent"):
293                    v.parent = self
294                    v.arg_key = arg_key
295
296    @property
297    def depth(self):
298        """
299        Returns the depth of this tree.
300        """
301        if self.parent:
302            return self.parent.depth + 1
303        return 0
304
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs
315
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)
328
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression
343
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)
358
359    @property
360    def parent_select(self):
361        """
362        Returns the parent select statement.
363        """
364        return self.find_ancestor(Select)
365
366    @property
367    def same_parent(self):
368        """Returns if the parent is the same class as itself."""
369        return type(self.parent) is self.__class__
370
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression
379
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)
397
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)
413
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))
433
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression
442
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self
450
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())
456
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node
466
467    def __str__(self):
468        return self.sql()
469
470    def __repr__(self):
471        return self._to_s()
472
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)
487
488    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
489        indent = "" if not level else "\n"
490        indent += "".join(["  "] * level)
491        left = f"({self.key.upper()} "
492
493        args: t.Dict[str, t.Any] = {
494            k: ", ".join(
495                v._to_s(hide_missing=hide_missing, level=level + 1)
496                if hasattr(v, "_to_s")
497                else str(v)
498                for v in ensure_list(vs)
499                if v is not None
500            )
501            for k, vs in self.args.items()
502        }
503        args["comments"] = self.comments
504        args["type"] = self.type
505        args = {k: v for k, v in args.items() if v or not hide_missing}
506
507        right = ", ".join(f"{k}: {v}" for k, v in args.items())
508        right += ")"
509
510        return indent + left + right
511
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node
538
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression
565
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self
575
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self
592
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors
626
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)
634
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression

Returns the first non parenthesis child or self.

def unalias(self):
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
653class Condition(Expression):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)
672
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)
691
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self):
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Returns:

Not: the new condition.

class Predicate(Condition):
706class Predicate(Condition):
707    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
710class DerivedTable(Expression):
711    @property
712    def alias_column_names(self):
713        table_alias = self.args.get("alias")
714        if not table_alias:
715            return []
716        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
717        return [c.name for c in column_list]
718
719    @property
720    def selects(self):
721        alias = self.args.get("alias")
722
723        if alias:
724            return alias.columns
725        return []
726
727    @property
728    def named_selects(self):
729        return [select.output_name for select in self.selects]
class Unionable(Expression):
732class Unionable(Expression):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
752
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
772
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
794class UDTF(DerivedTable, Unionable):
795    pass
class Cache(Expression):
798class Cache(Expression):
799    arg_types = {
800        "with": False,
801        "this": True,
802        "lazy": False,
803        "options": False,
804        "expression": False,
805    }
class Uncache(Expression):
808class Uncache(Expression):
809    arg_types = {"this": True, "exists": False}
class Create(Expression):
812class Create(Expression):
813    arg_types = {
814        "with": False,
815        "this": True,
816        "kind": True,
817        "expression": False,
818        "exists": False,
819        "properties": False,
820        "replace": False,
821        "unique": False,
822        "volatile": False,
823        "indexes": False,
824        "no_schema_binding": False,
825        "begin": False,
826    }
class Describe(Expression):
829class Describe(Expression):
830    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
833class Pragma(Expression):
834    pass
class Set(Expression):
837class Set(Expression):
838    arg_types = {"expressions": False}
class SetItem(Expression):
841class SetItem(Expression):
842    arg_types = {
843        "this": False,
844        "expressions": False,
845        "kind": False,
846        "collate": False,  # MySQL SET NAMES statement
847        "global": False,
848    }
class Show(Expression):
851class Show(Expression):
852    arg_types = {
853        "this": True,
854        "target": False,
855        "offset": False,
856        "limit": False,
857        "like": False,
858        "where": False,
859        "db": False,
860        "full": False,
861        "mutex": False,
862        "query": False,
863        "channel": False,
864        "global": False,
865        "log": False,
866        "position": False,
867        "types": False,
868    }
class UserDefinedFunction(Expression):
871class UserDefinedFunction(Expression):
872    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
875class CharacterSet(Expression):
876    arg_types = {"this": True, "default": False}
class With(Expression):
879class With(Expression):
880    arg_types = {"expressions": True, "recursive": False}
881
882    @property
883    def recursive(self) -> bool:
884        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
887class WithinGroup(Expression):
888    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
891class CTE(DerivedTable):
892    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
895class TableAlias(Expression):
896    arg_types = {"this": False, "columns": False}
897
898    @property
899    def columns(self):
900        return self.args.get("columns") or []
class BitString(Condition):
903class BitString(Condition):
904    pass
class HexString(Condition):
907class HexString(Condition):
908    pass
class ByteString(Condition):
911class ByteString(Condition):
912    pass
class Column(Condition):
915class Column(Condition):
916    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
917
918    @property
919    def table(self) -> str:
920        return self.text("table")
921
922    @property
923    def db(self) -> str:
924        return self.text("db")
925
926    @property
927    def catalog(self) -> str:
928        return self.text("catalog")
929
930    @property
931    def output_name(self) -> str:
932        return self.name
933
934    @property
935    def parts(self) -> t.List[Identifier]:
936        """Return the parts of a column in order catalog, db, table, name."""
937        return [part for part in reversed(list(self.args.values())) if part]
938
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnDef(Expression):
952class ColumnDef(Expression):
953    arg_types = {
954        "this": True,
955        "kind": False,
956        "constraints": False,
957        "exists": False,
958    }
class AlterColumn(Expression):
961class AlterColumn(Expression):
962    arg_types = {
963        "this": True,
964        "dtype": False,
965        "collate": False,
966        "using": False,
967        "default": False,
968        "drop": False,
969    }
class RenameTable(Expression):
972class RenameTable(Expression):
973    pass
class SetTag(Expression):
976class SetTag(Expression):
977    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
980class Comment(Expression):
981    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
984class ColumnConstraint(Expression):
985    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
988class ColumnConstraintKind(Expression):
989    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
992class AutoIncrementColumnConstraint(ColumnConstraintKind):
993    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
996class CaseSpecificColumnConstraint(ColumnConstraintKind):
997    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1000class CharacterSetColumnConstraint(ColumnConstraintKind):
1001    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1004class CheckColumnConstraint(ColumnConstraintKind):
1005    pass
class CollateColumnConstraint(ColumnConstraintKind):
1008class CollateColumnConstraint(ColumnConstraintKind):
1009    pass
class CommentColumnConstraint(ColumnConstraintKind):
1012class CommentColumnConstraint(ColumnConstraintKind):
1013    pass
class CompressColumnConstraint(ColumnConstraintKind):
1016class CompressColumnConstraint(ColumnConstraintKind):
1017    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1020class DateFormatColumnConstraint(ColumnConstraintKind):
1021    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1024class DefaultColumnConstraint(ColumnConstraintKind):
1025    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1028class EncodeColumnConstraint(ColumnConstraintKind):
1029    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1032class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1033    # this: True -> ALWAYS, this: False -> BY DEFAULT
1034    arg_types = {
1035        "this": False,
1036        "start": False,
1037        "increment": False,
1038        "minvalue": False,
1039        "maxvalue": False,
1040        "cycle": False,
1041    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1044class InlineLengthColumnConstraint(ColumnConstraintKind):
1045    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1048class NotNullColumnConstraint(ColumnConstraintKind):
1049    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1052class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1053    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1056class TitleColumnConstraint(ColumnConstraintKind):
1057    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1060class UniqueColumnConstraint(ColumnConstraintKind):
1061    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1064class UppercaseColumnConstraint(ColumnConstraintKind):
1065    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1068class PathColumnConstraint(ColumnConstraintKind):
1069    pass
class Constraint(Expression):
1072class Constraint(Expression):
1073    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1076class Delete(Expression):
1077    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1078
1079    def delete(
1080        self,
1081        table: ExpOrStr,
1082        dialect: DialectType = None,
1083        copy: bool = True,
1084        **opts,
1085    ) -> Delete:
1086        """
1087        Create a DELETE expression or replace the table on an existing DELETE expression.
1088
1089        Example:
1090            >>> delete("tbl").sql()
1091            'DELETE FROM tbl'
1092
1093        Args:
1094            table: the table from which to delete.
1095            dialect: the dialect used to parse the input expression.
1096            copy: if `False`, modify this expression instance in-place.
1097            opts: other options to use to parse the input expressions.
1098
1099        Returns:
1100            Delete: the modified expression.
1101        """
1102        return _apply_builder(
1103            expression=table,
1104            instance=self,
1105            arg="this",
1106            dialect=dialect,
1107            into=Table,
1108            copy=copy,
1109            **opts,
1110        )
1111
1112    def where(
1113        self,
1114        *expressions: ExpOrStr,
1115        append: bool = True,
1116        dialect: DialectType = None,
1117        copy: bool = True,
1118        **opts,
1119    ) -> Delete:
1120        """
1121        Append to or set the WHERE expressions.
1122
1123        Example:
1124            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1125            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1126
1127        Args:
1128            *expressions: the SQL code strings to parse.
1129                If an `Expression` instance is passed, it will be used as-is.
1130                Multiple expressions are combined with an AND operator.
1131            append: if `True`, AND the new expressions to any existing expression.
1132                Otherwise, this resets the expression.
1133            dialect: the dialect used to parse the input expressions.
1134            copy: if `False`, modify this expression instance in-place.
1135            opts: other options to use to parse the input expressions.
1136
1137        Returns:
1138            Delete: the modified expression.
1139        """
1140        return _apply_conjunction_builder(
1141            *expressions,
1142            instance=self,
1143            arg="where",
1144            append=append,
1145            into=Where,
1146            dialect=dialect,
1147            copy=copy,
1148            **opts,
1149        )
1150
1151    def returning(
1152        self,
1153        expression: ExpOrStr,
1154        dialect: DialectType = None,
1155        copy: bool = True,
1156        **opts,
1157    ) -> Delete:
1158        """
1159        Set the RETURNING expression. Not supported by all dialects.
1160
1161        Example:
1162            >>> delete("tbl").returning("*", dialect="postgres").sql()
1163            'DELETE FROM tbl RETURNING *'
1164
1165        Args:
1166            expression: the SQL code strings to parse.
1167                If an `Expression` instance is passed, it will be used as-is.
1168            dialect: the dialect used to parse the input expressions.
1169            copy: if `False`, modify this expression instance in-place.
1170            opts: other options to use to parse the input expressions.
1171
1172        Returns:
1173            Delete: the modified expression.
1174        """
1175        return _apply_builder(
1176            expression=expression,
1177            instance=self,
1178            arg="returning",
1179            prefix="RETURNING",
1180            dialect=dialect,
1181            copy=copy,
1182            into=Returning,
1183            **opts,
1184        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1079    def delete(
1080        self,
1081        table: ExpOrStr,
1082        dialect: DialectType = None,
1083        copy: bool = True,
1084        **opts,
1085    ) -> Delete:
1086        """
1087        Create a DELETE expression or replace the table on an existing DELETE expression.
1088
1089        Example:
1090            >>> delete("tbl").sql()
1091            'DELETE FROM tbl'
1092
1093        Args:
1094            table: the table from which to delete.
1095            dialect: the dialect used to parse the input expression.
1096            copy: if `False`, modify this expression instance in-place.
1097            opts: other options to use to parse the input expressions.
1098
1099        Returns:
1100            Delete: the modified expression.
1101        """
1102        return _apply_builder(
1103            expression=table,
1104            instance=self,
1105            arg="this",
1106            dialect=dialect,
1107            into=Table,
1108            copy=copy,
1109            **opts,
1110        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1112    def where(
1113        self,
1114        *expressions: ExpOrStr,
1115        append: bool = True,
1116        dialect: DialectType = None,
1117        copy: bool = True,
1118        **opts,
1119    ) -> Delete:
1120        """
1121        Append to or set the WHERE expressions.
1122
1123        Example:
1124            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1125            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1126
1127        Args:
1128            *expressions: the SQL code strings to parse.
1129                If an `Expression` instance is passed, it will be used as-is.
1130                Multiple expressions are combined with an AND operator.
1131            append: if `True`, AND the new expressions to any existing expression.
1132                Otherwise, this resets the expression.
1133            dialect: the dialect used to parse the input expressions.
1134            copy: if `False`, modify this expression instance in-place.
1135            opts: other options to use to parse the input expressions.
1136
1137        Returns:
1138            Delete: the modified expression.
1139        """
1140        return _apply_conjunction_builder(
1141            *expressions,
1142            instance=self,
1143            arg="where",
1144            append=append,
1145            into=Where,
1146            dialect=dialect,
1147            copy=copy,
1148            **opts,
1149        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1151    def returning(
1152        self,
1153        expression: ExpOrStr,
1154        dialect: DialectType = None,
1155        copy: bool = True,
1156        **opts,
1157    ) -> Delete:
1158        """
1159        Set the RETURNING expression. Not supported by all dialects.
1160
1161        Example:
1162            >>> delete("tbl").returning("*", dialect="postgres").sql()
1163            'DELETE FROM tbl RETURNING *'
1164
1165        Args:
1166            expression: the SQL code strings to parse.
1167                If an `Expression` instance is passed, it will be used as-is.
1168            dialect: the dialect used to parse the input expressions.
1169            copy: if `False`, modify this expression instance in-place.
1170            opts: other options to use to parse the input expressions.
1171
1172        Returns:
1173            Delete: the modified expression.
1174        """
1175        return _apply_builder(
1176            expression=expression,
1177            instance=self,
1178            arg="returning",
1179            prefix="RETURNING",
1180            dialect=dialect,
1181            copy=copy,
1182            into=Returning,
1183            **opts,
1184        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1187class Drop(Expression):
1188    arg_types = {
1189        "this": False,
1190        "kind": False,
1191        "exists": False,
1192        "temporary": False,
1193        "materialized": False,
1194        "cascade": False,
1195        "constraints": False,
1196    }
class Filter(Expression):
1199class Filter(Expression):
1200    arg_types = {"this": True, "expression": True}
class Check(Expression):
1203class Check(Expression):
1204    pass
class Directory(Expression):
1207class Directory(Expression):
1208    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1209    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1212class ForeignKey(Expression):
1213    arg_types = {
1214        "expressions": True,
1215        "reference": False,
1216        "delete": False,
1217        "update": False,
1218    }
class PrimaryKey(Expression):
1221class PrimaryKey(Expression):
1222    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1225class Unique(Expression):
1226    arg_types = {"expressions": True}
class Into(Expression):
1231class Into(Expression):
1232    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1235class From(Expression):
1236    arg_types = {"expressions": True}
class Having(Expression):
1239class Having(Expression):
1240    pass
class Hint(Expression):
1243class Hint(Expression):
1244    arg_types = {"expressions": True}
class JoinHint(Expression):
1247class JoinHint(Expression):
1248    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1251class Identifier(Expression):
1252    arg_types = {"this": True, "quoted": False}
1253
1254    @property
1255    def quoted(self):
1256        return bool(self.args.get("quoted"))
1257
1258    @property
1259    def hashable_args(self) -> t.Any:
1260        if self.quoted and any(char.isupper() for char in self.this):
1261            return (self.this, self.quoted)
1262        return self.this.lower()
1263
1264    @property
1265    def output_name(self):
1266        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1269class Index(Expression):
1270    arg_types = {
1271        "this": False,
1272        "table": False,
1273        "where": False,
1274        "columns": False,
1275        "unique": False,
1276        "primary": False,
1277        "amp": False,  # teradata
1278    }
class Insert(Expression):
1281class Insert(Expression):
1282    arg_types = {
1283        "with": False,
1284        "this": True,
1285        "expression": False,
1286        "returning": False,
1287        "overwrite": False,
1288        "exists": False,
1289        "partition": False,
1290        "alternative": False,
1291    }
class Returning(Expression):
1294class Returning(Expression):
1295    arg_types = {"expressions": True}
class Introducer(Expression):
1299class Introducer(Expression):
1300    arg_types = {"this": True, "expression": True}
class National(Expression):
1304class National(Expression):
1305    pass
class LoadData(Expression):
1308class LoadData(Expression):
1309    arg_types = {
1310        "this": True,
1311        "local": False,
1312        "overwrite": False,
1313        "inpath": True,
1314        "partition": False,
1315        "input_format": False,
1316        "serde": False,
1317    }
class Partition(Expression):
1320class Partition(Expression):
1321    arg_types = {"expressions": True}
class Fetch(Expression):
1324class Fetch(Expression):
1325    arg_types = {"direction": False, "count": False}
class Group(Expression):
1328class Group(Expression):
1329    arg_types = {
1330        "expressions": False,
1331        "grouping_sets": False,
1332        "cube": False,
1333        "rollup": False,
1334    }
class Lambda(Expression):
1337class Lambda(Expression):
1338    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1341class Limit(Expression):
1342    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1345class Literal(Condition):
1346    arg_types = {"this": True, "is_string": True}
1347
1348    @property
1349    def hashable_args(self) -> t.Any:
1350        return (self.this, self.args.get("is_string"))
1351
1352    @classmethod
1353    def number(cls, number) -> Literal:
1354        return cls(this=str(number), is_string=False)
1355
1356    @classmethod
1357    def string(cls, string) -> Literal:
1358        return cls(this=str(string), is_string=True)
1359
1360    @property
1361    def output_name(self):
1362        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1352    @classmethod
1353    def number(cls, number) -> Literal:
1354        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1356    @classmethod
1357    def string(cls, string) -> Literal:
1358        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1365class Join(Expression):
1366    arg_types = {
1367        "this": True,
1368        "on": False,
1369        "side": False,
1370        "kind": False,
1371        "using": False,
1372        "natural": False,
1373    }
1374
1375    @property
1376    def kind(self):
1377        return self.text("kind").upper()
1378
1379    @property
1380    def side(self):
1381        return self.text("side").upper()
1382
1383    @property
1384    def alias_or_name(self):
1385        return self.this.alias_or_name
1386
1387    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1388        """
1389        Append to or set the ON expressions.
1390
1391        Example:
1392            >>> import sqlglot
1393            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1394            'JOIN x ON y = 1'
1395
1396        Args:
1397            *expressions (str | Expression): the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399                Multiple expressions are combined with an AND operator.
1400            append (bool): if `True`, AND the new expressions to any existing expression.
1401                Otherwise, this resets the expression.
1402            dialect (str): the dialect used to parse the input expressions.
1403            copy (bool): if `False`, modify this expression instance in-place.
1404            opts (kwargs): other options to use to parse the input expressions.
1405
1406        Returns:
1407            Join: the modified join expression.
1408        """
1409        join = _apply_conjunction_builder(
1410            *expressions,
1411            instance=self,
1412            arg="on",
1413            append=append,
1414            dialect=dialect,
1415            copy=copy,
1416            **opts,
1417        )
1418
1419        if join.kind == "CROSS":
1420            join.set("kind", None)
1421
1422        return join
1423
1424    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1425        """
1426        Append to or set the USING expressions.
1427
1428        Example:
1429            >>> import sqlglot
1430            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1431            'JOIN x USING (foo, bla)'
1432
1433        Args:
1434            *expressions (str | Expression): the SQL code strings to parse.
1435                If an `Expression` instance is passed, it will be used as-is.
1436            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1437                Otherwise, this resets the expression.
1438            dialect (str): the dialect used to parse the input expressions.
1439            copy (bool): if `False`, modify this expression instance in-place.
1440            opts (kwargs): other options to use to parse the input expressions.
1441
1442        Returns:
1443            Join: the modified join expression.
1444        """
1445        join = _apply_list_builder(
1446            *expressions,
1447            instance=self,
1448            arg="using",
1449            append=append,
1450            dialect=dialect,
1451            copy=copy,
1452            **opts,
1453        )
1454
1455        if join.kind == "CROSS":
1456            join.set("kind", None)
1457
1458        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1387    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1388        """
1389        Append to or set the ON expressions.
1390
1391        Example:
1392            >>> import sqlglot
1393            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1394            'JOIN x ON y = 1'
1395
1396        Args:
1397            *expressions (str | Expression): the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399                Multiple expressions are combined with an AND operator.
1400            append (bool): if `True`, AND the new expressions to any existing expression.
1401                Otherwise, this resets the expression.
1402            dialect (str): the dialect used to parse the input expressions.
1403            copy (bool): if `False`, modify this expression instance in-place.
1404            opts (kwargs): other options to use to parse the input expressions.
1405
1406        Returns:
1407            Join: the modified join expression.
1408        """
1409        join = _apply_conjunction_builder(
1410            *expressions,
1411            instance=self,
1412            arg="on",
1413            append=append,
1414            dialect=dialect,
1415            copy=copy,
1416            **opts,
1417        )
1418
1419        if join.kind == "CROSS":
1420            join.set("kind", None)
1421
1422        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1424    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1425        """
1426        Append to or set the USING expressions.
1427
1428        Example:
1429            >>> import sqlglot
1430            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1431            'JOIN x USING (foo, bla)'
1432
1433        Args:
1434            *expressions (str | Expression): the SQL code strings to parse.
1435                If an `Expression` instance is passed, it will be used as-is.
1436            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1437                Otherwise, this resets the expression.
1438            dialect (str): the dialect used to parse the input expressions.
1439            copy (bool): if `False`, modify this expression instance in-place.
1440            opts (kwargs): other options to use to parse the input expressions.
1441
1442        Returns:
1443            Join: the modified join expression.
1444        """
1445        join = _apply_list_builder(
1446            *expressions,
1447            instance=self,
1448            arg="using",
1449            append=append,
1450            dialect=dialect,
1451            copy=copy,
1452            **opts,
1453        )
1454
1455        if join.kind == "CROSS":
1456            join.set("kind", None)
1457
1458        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1461class Lateral(UDTF):
1462    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1465class MatchRecognize(Expression):
1466    arg_types = {
1467        "partition_by": False,
1468        "order": False,
1469        "measures": False,
1470        "rows": False,
1471        "after": False,
1472        "pattern": False,
1473        "define": False,
1474    }
class Final(Expression):
1479class Final(Expression):
1480    pass
class Offset(Expression):
1483class Offset(Expression):
1484    arg_types = {"this": False, "expression": True}
class Order(Expression):
1487class Order(Expression):
1488    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1493class Cluster(Order):
1494    pass
class Distribute(Order):
1497class Distribute(Order):
1498    pass
class Sort(Order):
1501class Sort(Order):
1502    pass
class Ordered(Expression):
1505class Ordered(Expression):
1506    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1509class Property(Expression):
1510    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1513class AfterJournalProperty(Property):
1514    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1517class AlgorithmProperty(Property):
1518    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1521class AutoIncrementProperty(Property):
1522    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1525class BlockCompressionProperty(Property):
1526    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1529class CharacterSetProperty(Property):
1530    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1533class ChecksumProperty(Property):
1534    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1537class CollateProperty(Property):
1538    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1541class DataBlocksizeProperty(Property):
1542    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1545class DefinerProperty(Property):
1546    arg_types = {"this": True}
class DistKeyProperty(Property):
1549class DistKeyProperty(Property):
1550    arg_types = {"this": True}
class DistStyleProperty(Property):
1553class DistStyleProperty(Property):
1554    arg_types = {"this": True}
class EngineProperty(Property):
1557class EngineProperty(Property):
1558    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1561class ExecuteAsProperty(Property):
1562    arg_types = {"this": True}
class ExternalProperty(Property):
1565class ExternalProperty(Property):
1566    arg_types = {"this": False}
class FallbackProperty(Property):
1569class FallbackProperty(Property):
1570    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1573class FileFormatProperty(Property):
1574    arg_types = {"this": True}
class FreespaceProperty(Property):
1577class FreespaceProperty(Property):
1578    arg_types = {"this": True, "percent": False}
class IsolatedLoadingProperty(Property):
1581class IsolatedLoadingProperty(Property):
1582    arg_types = {
1583        "no": True,
1584        "concurrent": True,
1585        "for_all": True,
1586        "for_insert": True,
1587        "for_none": True,
1588    }
class JournalProperty(Property):
1591class JournalProperty(Property):
1592    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1595class LanguageProperty(Property):
1596    arg_types = {"this": True}
class LikeProperty(Property):
1599class LikeProperty(Property):
1600    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1603class LocationProperty(Property):
1604    arg_types = {"this": True}
class LockingProperty(Property):
1607class LockingProperty(Property):
1608    arg_types = {
1609        "this": False,
1610        "kind": True,
1611        "for_or_in": True,
1612        "lock_type": True,
1613        "override": False,
1614    }
class LogProperty(Property):
1617class LogProperty(Property):
1618    arg_types = {"no": True}
class MaterializedProperty(Property):
1621class MaterializedProperty(Property):
1622    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1625class MergeBlockRatioProperty(Property):
1626    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1629class NoPrimaryIndexProperty(Property):
1630    arg_types = {"this": False}
class OnCommitProperty(Property):
1633class OnCommitProperty(Property):
1634    arg_type = {"this": False}
class PartitionedByProperty(Property):
1637class PartitionedByProperty(Property):
1638    arg_types = {"this": True}
class ReturnsProperty(Property):
1641class ReturnsProperty(Property):
1642    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1645class RowFormatDelimitedProperty(Property):
1646    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1647    arg_types = {
1648        "fields": False,
1649        "escaped": False,
1650        "collection_items": False,
1651        "map_keys": False,
1652        "lines": False,
1653        "null": False,
1654        "serde": False,
1655    }
class RowFormatSerdeProperty(Property):
1658class RowFormatSerdeProperty(Property):
1659    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1662class SchemaCommentProperty(Property):
1663    arg_types = {"this": True}
class SerdeProperties(Property):
1666class SerdeProperties(Property):
1667    arg_types = {"expressions": True}
class SetProperty(Property):
1670class SetProperty(Property):
1671    arg_types = {"multi": True}
class SortKeyProperty(Property):
1674class SortKeyProperty(Property):
1675    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1678class SqlSecurityProperty(Property):
1679    arg_types = {"definer": True}
class TableFormatProperty(Property):
1682class TableFormatProperty(Property):
1683    arg_types = {"this": True}
class TemporaryProperty(Property):
1686class TemporaryProperty(Property):
1687    arg_types = {"global_": True}
class TransientProperty(Property):
1690class TransientProperty(Property):
1691    arg_types = {"this": False}
class VolatilityProperty(Property):
1694class VolatilityProperty(Property):
1695    arg_types = {"this": True}
class WithDataProperty(Property):
1698class WithDataProperty(Property):
1699    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1702class WithJournalTableProperty(Property):
1703    arg_types = {"this": True}
class Properties(Expression):
1706class Properties(Expression):
1707    arg_types = {"expressions": True}
1708
1709    NAME_TO_PROPERTY = {
1710        "ALGORITHM": AlgorithmProperty,
1711        "AUTO_INCREMENT": AutoIncrementProperty,
1712        "CHARACTER SET": CharacterSetProperty,
1713        "COLLATE": CollateProperty,
1714        "COMMENT": SchemaCommentProperty,
1715        "DEFINER": DefinerProperty,
1716        "DISTKEY": DistKeyProperty,
1717        "DISTSTYLE": DistStyleProperty,
1718        "ENGINE": EngineProperty,
1719        "EXECUTE AS": ExecuteAsProperty,
1720        "FORMAT": FileFormatProperty,
1721        "LANGUAGE": LanguageProperty,
1722        "LOCATION": LocationProperty,
1723        "PARTITIONED_BY": PartitionedByProperty,
1724        "RETURNS": ReturnsProperty,
1725        "SORTKEY": SortKeyProperty,
1726        "TABLE_FORMAT": TableFormatProperty,
1727    }
1728
1729    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1730
1731    # CREATE property locations
1732    # Form: schema specified
1733    #   create [POST_CREATE]
1734    #     table a [POST_NAME]
1735    #     (b int) [POST_SCHEMA]
1736    #     with ([POST_WITH])
1737    #     index (b) [POST_INDEX]
1738    #
1739    # Form: alias selection
1740    #   create [POST_CREATE]
1741    #     table a [POST_NAME]
1742    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1743    #     index (c) [POST_INDEX]
1744    class Location(AutoName):
1745        POST_CREATE = auto()
1746        POST_NAME = auto()
1747        POST_SCHEMA = auto()
1748        POST_WITH = auto()
1749        POST_ALIAS = auto()
1750        POST_EXPRESSION = auto()
1751        POST_INDEX = auto()
1752        UNSUPPORTED = auto()
1753
1754    @classmethod
1755    def from_dict(cls, properties_dict) -> Properties:
1756        expressions = []
1757        for key, value in properties_dict.items():
1758            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1759            if property_cls:
1760                expressions.append(property_cls(this=convert(value)))
1761            else:
1762                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1763
1764        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1754    @classmethod
1755    def from_dict(cls, properties_dict) -> Properties:
1756        expressions = []
1757        for key, value in properties_dict.items():
1758            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1759            if property_cls:
1760                expressions.append(property_cls(this=convert(value)))
1761            else:
1762                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1763
1764        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1744    class Location(AutoName):
1745        POST_CREATE = auto()
1746        POST_NAME = auto()
1747        POST_SCHEMA = auto()
1748        POST_WITH = auto()
1749        POST_ALIAS = auto()
1750        POST_EXPRESSION = auto()
1751        POST_INDEX = auto()
1752        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1767class Qualify(Expression):
1768    pass
class Return(Expression):
1772class Return(Expression):
1773    pass
class Reference(Expression):
1776class Reference(Expression):
1777    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1780class Tuple(Expression):
1781    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1784class Subqueryable(Unionable):
1785    def subquery(self, alias=None, copy=True) -> Subquery:
1786        """
1787        Convert this expression to an aliased expression that can be used as a Subquery.
1788
1789        Example:
1790            >>> subquery = Select().select("x").from_("tbl").subquery()
1791            >>> Select().select("x").from_(subquery).sql()
1792            'SELECT x FROM (SELECT x FROM tbl)'
1793
1794        Args:
1795            alias (str | Identifier): an optional alias for the subquery
1796            copy (bool): if `False`, modify this expression instance in-place.
1797
1798        Returns:
1799            Alias: the subquery
1800        """
1801        instance = _maybe_copy(self, copy)
1802        return Subquery(
1803            this=instance,
1804            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1805        )
1806
1807    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1808        raise NotImplementedError
1809
1810    @property
1811    def ctes(self):
1812        with_ = self.args.get("with")
1813        if not with_:
1814            return []
1815        return with_.expressions
1816
1817    @property
1818    def selects(self):
1819        raise NotImplementedError("Subqueryable objects must implement `selects`")
1820
1821    @property
1822    def named_selects(self):
1823        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1824
1825    def with_(
1826        self,
1827        alias,
1828        as_,
1829        recursive=None,
1830        append=True,
1831        dialect=None,
1832        copy=True,
1833        **opts,
1834    ):
1835        """
1836        Append to or set the common table expressions.
1837
1838        Example:
1839            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1840            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1841
1842        Args:
1843            alias (str | Expression): the SQL code string to parse as the table name.
1844                If an `Expression` instance is passed, this is used as-is.
1845            as_ (str | Expression): the SQL code string to parse as the table expression.
1846                If an `Expression` instance is passed, it will be used as-is.
1847            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1848            append (bool): if `True`, add to any existing expressions.
1849                Otherwise, this resets the expressions.
1850            dialect (str): the dialect used to parse the input expression.
1851            copy (bool): if `False`, modify this expression instance in-place.
1852            opts (kwargs): other options to use to parse the input expressions.
1853
1854        Returns:
1855            Select: the modified expression.
1856        """
1857        alias_expression = maybe_parse(
1858            alias,
1859            dialect=dialect,
1860            into=TableAlias,
1861            **opts,
1862        )
1863        as_expression = maybe_parse(
1864            as_,
1865            dialect=dialect,
1866            **opts,
1867        )
1868        cte = CTE(
1869            this=as_expression,
1870            alias=alias_expression,
1871        )
1872        return _apply_child_list_builder(
1873            cte,
1874            instance=self,
1875            arg="with",
1876            append=append,
1877            copy=copy,
1878            into=With,
1879            properties={"recursive": recursive or False},
1880        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1785    def subquery(self, alias=None, copy=True) -> Subquery:
1786        """
1787        Convert this expression to an aliased expression that can be used as a Subquery.
1788
1789        Example:
1790            >>> subquery = Select().select("x").from_("tbl").subquery()
1791            >>> Select().select("x").from_(subquery).sql()
1792            'SELECT x FROM (SELECT x FROM tbl)'
1793
1794        Args:
1795            alias (str | Identifier): an optional alias for the subquery
1796            copy (bool): if `False`, modify this expression instance in-place.
1797
1798        Returns:
1799            Alias: the subquery
1800        """
1801        instance = _maybe_copy(self, copy)
1802        return Subquery(
1803            this=instance,
1804            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1805        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1807    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1808        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1825    def with_(
1826        self,
1827        alias,
1828        as_,
1829        recursive=None,
1830        append=True,
1831        dialect=None,
1832        copy=True,
1833        **opts,
1834    ):
1835        """
1836        Append to or set the common table expressions.
1837
1838        Example:
1839            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1840            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1841
1842        Args:
1843            alias (str | Expression): the SQL code string to parse as the table name.
1844                If an `Expression` instance is passed, this is used as-is.
1845            as_ (str | Expression): the SQL code string to parse as the table expression.
1846                If an `Expression` instance is passed, it will be used as-is.
1847            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1848            append (bool): if `True`, add to any existing expressions.
1849                Otherwise, this resets the expressions.
1850            dialect (str): the dialect used to parse the input expression.
1851            copy (bool): if `False`, modify this expression instance in-place.
1852            opts (kwargs): other options to use to parse the input expressions.
1853
1854        Returns:
1855            Select: the modified expression.
1856        """
1857        alias_expression = maybe_parse(
1858            alias,
1859            dialect=dialect,
1860            into=TableAlias,
1861            **opts,
1862        )
1863        as_expression = maybe_parse(
1864            as_,
1865            dialect=dialect,
1866            **opts,
1867        )
1868        cte = CTE(
1869            this=as_expression,
1870            alias=alias_expression,
1871        )
1872        return _apply_child_list_builder(
1873            cte,
1874            instance=self,
1875            arg="with",
1876            append=append,
1877            copy=copy,
1878            into=With,
1879            properties={"recursive": recursive or False},
1880        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1904class Table(Expression):
1905    arg_types = {
1906        "this": True,
1907        "alias": False,
1908        "db": False,
1909        "catalog": False,
1910        "laterals": False,
1911        "joins": False,
1912        "pivots": False,
1913        "hints": False,
1914        "system_time": False,
1915    }
1916
1917    @property
1918    def db(self) -> str:
1919        return self.text("db")
1920
1921    @property
1922    def catalog(self) -> str:
1923        return self.text("catalog")
class SystemTime(Expression):
1927class SystemTime(Expression):
1928    arg_types = {
1929        "this": False,
1930        "expression": False,
1931        "kind": True,
1932    }
class Union(Subqueryable):
1935class Union(Subqueryable):
1936    arg_types = {
1937        "with": False,
1938        "this": True,
1939        "expression": True,
1940        "distinct": False,
1941        **QUERY_MODIFIERS,
1942    }
1943
1944    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1945        """
1946        Set the LIMIT expression.
1947
1948        Example:
1949            >>> select("1").union(select("1")).limit(1).sql()
1950            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1951
1952        Args:
1953            expression (str | int | Expression): the SQL code string to parse.
1954                This can also be an integer.
1955                If a `Limit` instance is passed, this is used as-is.
1956                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1957            dialect (str): the dialect used to parse the input expression.
1958            copy (bool): if `False`, modify this expression instance in-place.
1959            opts (kwargs): other options to use to parse the input expressions.
1960
1961        Returns:
1962            Select: The limited subqueryable.
1963        """
1964        return (
1965            select("*")
1966            .from_(self.subquery(alias="_l_0", copy=copy))
1967            .limit(expression, dialect=dialect, copy=False, **opts)
1968        )
1969
1970    def select(
1971        self,
1972        *expressions: ExpOrStr,
1973        append: bool = True,
1974        dialect: DialectType = None,
1975        copy: bool = True,
1976        **opts,
1977    ) -> Union:
1978        """Append to or set the SELECT of the union recursively.
1979
1980        Example:
1981            >>> from sqlglot import parse_one
1982            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1983            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1984
1985        Args:
1986            *expressions: the SQL code strings to parse.
1987                If an `Expression` instance is passed, it will be used as-is.
1988            append: if `True`, add to any existing expressions.
1989                Otherwise, this resets the expressions.
1990            dialect: the dialect used to parse the input expressions.
1991            copy: if `False`, modify this expression instance in-place.
1992            opts: other options to use to parse the input expressions.
1993
1994        Returns:
1995            Union: the modified expression.
1996        """
1997        this = self.copy() if copy else self
1998        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1999        this.expression.unnest().select(
2000            *expressions, append=append, dialect=dialect, copy=False, **opts
2001        )
2002        return this
2003
2004    @property
2005    def named_selects(self):
2006        return self.this.unnest().named_selects
2007
2008    @property
2009    def is_star(self) -> bool:
2010        return self.this.is_star or self.expression.is_star
2011
2012    @property
2013    def selects(self):
2014        return self.this.unnest().selects
2015
2016    @property
2017    def left(self):
2018        return self.this
2019
2020    @property
2021    def right(self):
2022        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1944    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1945        """
1946        Set the LIMIT expression.
1947
1948        Example:
1949            >>> select("1").union(select("1")).limit(1).sql()
1950            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1951
1952        Args:
1953            expression (str | int | Expression): the SQL code string to parse.
1954                This can also be an integer.
1955                If a `Limit` instance is passed, this is used as-is.
1956                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1957            dialect (str): the dialect used to parse the input expression.
1958            copy (bool): if `False`, modify this expression instance in-place.
1959            opts (kwargs): other options to use to parse the input expressions.
1960
1961        Returns:
1962            Select: The limited subqueryable.
1963        """
1964        return (
1965            select("*")
1966            .from_(self.subquery(alias="_l_0", copy=copy))
1967            .limit(expression, dialect=dialect, copy=False, **opts)
1968        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
1970    def select(
1971        self,
1972        *expressions: ExpOrStr,
1973        append: bool = True,
1974        dialect: DialectType = None,
1975        copy: bool = True,
1976        **opts,
1977    ) -> Union:
1978        """Append to or set the SELECT of the union recursively.
1979
1980        Example:
1981            >>> from sqlglot import parse_one
1982            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1983            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1984
1985        Args:
1986            *expressions: the SQL code strings to parse.
1987                If an `Expression` instance is passed, it will be used as-is.
1988            append: if `True`, add to any existing expressions.
1989                Otherwise, this resets the expressions.
1990            dialect: the dialect used to parse the input expressions.
1991            copy: if `False`, modify this expression instance in-place.
1992            opts: other options to use to parse the input expressions.
1993
1994        Returns:
1995            Union: the modified expression.
1996        """
1997        this = self.copy() if copy else self
1998        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1999        this.expression.unnest().select(
2000            *expressions, append=append, dialect=dialect, copy=False, **opts
2001        )
2002        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2025class Except(Union):
2026    pass
class Intersect(Union):
2029class Intersect(Union):
2030    pass
class Unnest(UDTF):
2033class Unnest(UDTF):
2034    arg_types = {
2035        "expressions": True,
2036        "ordinality": False,
2037        "alias": False,
2038        "offset": False,
2039    }
class Update(Expression):
2042class Update(Expression):
2043    arg_types = {
2044        "with": False,
2045        "this": False,
2046        "expressions": True,
2047        "from": False,
2048        "where": False,
2049        "returning": False,
2050    }
class Values(UDTF):
2053class Values(UDTF):
2054    arg_types = {
2055        "expressions": True,
2056        "ordinality": False,
2057        "alias": False,
2058    }
class Var(Expression):
2061class Var(Expression):
2062    pass
class Schema(Expression):
2065class Schema(Expression):
2066    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2071class Lock(Expression):
2072    arg_types = {"update": True}
class Select(Subqueryable):
2075class Select(Subqueryable):
2076    arg_types = {
2077        "with": False,
2078        "kind": False,
2079        "expressions": False,
2080        "hint": False,
2081        "distinct": False,
2082        "into": False,
2083        "from": False,
2084        **QUERY_MODIFIERS,
2085    }
2086
2087    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2088        """
2089        Set the FROM expression.
2090
2091        Example:
2092            >>> Select().from_("tbl").select("x").sql()
2093            'SELECT x FROM tbl'
2094
2095        Args:
2096            *expressions (str | Expression): the SQL code strings to parse.
2097                If a `From` instance is passed, this is used as-is.
2098                If another `Expression` instance is passed, it will be wrapped in a `From`.
2099            append (bool): if `True`, add to any existing expressions.
2100                Otherwise, this flattens all the `From` expression into a single expression.
2101            dialect (str): the dialect used to parse the input expression.
2102            copy (bool): if `False`, modify this expression instance in-place.
2103            opts (kwargs): other options to use to parse the input expressions.
2104
2105        Returns:
2106            Select: the modified expression.
2107        """
2108        return _apply_child_list_builder(
2109            *expressions,
2110            instance=self,
2111            arg="from",
2112            append=append,
2113            copy=copy,
2114            prefix="FROM",
2115            into=From,
2116            dialect=dialect,
2117            **opts,
2118        )
2119
2120    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2121        """
2122        Set the GROUP BY expression.
2123
2124        Example:
2125            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2126            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2127
2128        Args:
2129            *expressions (str | Expression): the SQL code strings to parse.
2130                If a `Group` instance is passed, this is used as-is.
2131                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2132                If nothing is passed in then a group by is not applied to the expression
2133            append (bool): if `True`, add to any existing expressions.
2134                Otherwise, this flattens all the `Group` expression into a single expression.
2135            dialect (str): the dialect used to parse the input expression.
2136            copy (bool): if `False`, modify this expression instance in-place.
2137            opts (kwargs): other options to use to parse the input expressions.
2138
2139        Returns:
2140            Select: the modified expression.
2141        """
2142        if not expressions:
2143            return self if not copy else self.copy()
2144        return _apply_child_list_builder(
2145            *expressions,
2146            instance=self,
2147            arg="group",
2148            append=append,
2149            copy=copy,
2150            prefix="GROUP BY",
2151            into=Group,
2152            dialect=dialect,
2153            **opts,
2154        )
2155
2156    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2157        """
2158        Set the ORDER BY expression.
2159
2160        Example:
2161            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2162            'SELECT x FROM tbl ORDER BY x DESC'
2163
2164        Args:
2165            *expressions (str | Expression): the SQL code strings to parse.
2166                If a `Group` instance is passed, this is used as-is.
2167                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2168            append (bool): if `True`, add to any existing expressions.
2169                Otherwise, this flattens all the `Order` expression into a single expression.
2170            dialect (str): the dialect used to parse the input expression.
2171            copy (bool): if `False`, modify this expression instance in-place.
2172            opts (kwargs): other options to use to parse the input expressions.
2173
2174        Returns:
2175            Select: the modified expression.
2176        """
2177        return _apply_child_list_builder(
2178            *expressions,
2179            instance=self,
2180            arg="order",
2181            append=append,
2182            copy=copy,
2183            prefix="ORDER BY",
2184            into=Order,
2185            dialect=dialect,
2186            **opts,
2187        )
2188
2189    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2190        """
2191        Set the SORT BY expression.
2192
2193        Example:
2194            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2195            'SELECT x FROM tbl SORT BY x DESC'
2196
2197        Args:
2198            *expressions (str | Expression): the SQL code strings to parse.
2199                If a `Group` instance is passed, this is used as-is.
2200                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2201            append (bool): if `True`, add to any existing expressions.
2202                Otherwise, this flattens all the `Order` expression into a single expression.
2203            dialect (str): the dialect used to parse the input expression.
2204            copy (bool): if `False`, modify this expression instance in-place.
2205            opts (kwargs): other options to use to parse the input expressions.
2206
2207        Returns:
2208            Select: the modified expression.
2209        """
2210        return _apply_child_list_builder(
2211            *expressions,
2212            instance=self,
2213            arg="sort",
2214            append=append,
2215            copy=copy,
2216            prefix="SORT BY",
2217            into=Sort,
2218            dialect=dialect,
2219            **opts,
2220        )
2221
2222    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2223        """
2224        Set the CLUSTER BY expression.
2225
2226        Example:
2227            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2228            'SELECT x FROM tbl CLUSTER BY x DESC'
2229
2230        Args:
2231            *expressions (str | Expression): the SQL code strings to parse.
2232                If a `Group` instance is passed, this is used as-is.
2233                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2234            append (bool): if `True`, add to any existing expressions.
2235                Otherwise, this flattens all the `Order` expression into a single expression.
2236            dialect (str): the dialect used to parse the input expression.
2237            copy (bool): if `False`, modify this expression instance in-place.
2238            opts (kwargs): other options to use to parse the input expressions.
2239
2240        Returns:
2241            Select: the modified expression.
2242        """
2243        return _apply_child_list_builder(
2244            *expressions,
2245            instance=self,
2246            arg="cluster",
2247            append=append,
2248            copy=copy,
2249            prefix="CLUSTER BY",
2250            into=Cluster,
2251            dialect=dialect,
2252            **opts,
2253        )
2254
2255    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2256        """
2257        Set the LIMIT expression.
2258
2259        Example:
2260            >>> Select().from_("tbl").select("x").limit(10).sql()
2261            'SELECT x FROM tbl LIMIT 10'
2262
2263        Args:
2264            expression (str | int | Expression): the SQL code string to parse.
2265                This can also be an integer.
2266                If a `Limit` instance is passed, this is used as-is.
2267                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2268            dialect (str): the dialect used to parse the input expression.
2269            copy (bool): if `False`, modify this expression instance in-place.
2270            opts (kwargs): other options to use to parse the input expressions.
2271
2272        Returns:
2273            Select: the modified expression.
2274        """
2275        return _apply_builder(
2276            expression=expression,
2277            instance=self,
2278            arg="limit",
2279            into=Limit,
2280            prefix="LIMIT",
2281            dialect=dialect,
2282            copy=copy,
2283            **opts,
2284        )
2285
2286    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2287        """
2288        Set the OFFSET expression.
2289
2290        Example:
2291            >>> Select().from_("tbl").select("x").offset(10).sql()
2292            'SELECT x FROM tbl OFFSET 10'
2293
2294        Args:
2295            expression (str | int | Expression): the SQL code string to parse.
2296                This can also be an integer.
2297                If a `Offset` instance is passed, this is used as-is.
2298                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2299            dialect (str): the dialect used to parse the input expression.
2300            copy (bool): if `False`, modify this expression instance in-place.
2301            opts (kwargs): other options to use to parse the input expressions.
2302
2303        Returns:
2304            Select: the modified expression.
2305        """
2306        return _apply_builder(
2307            expression=expression,
2308            instance=self,
2309            arg="offset",
2310            into=Offset,
2311            prefix="OFFSET",
2312            dialect=dialect,
2313            copy=copy,
2314            **opts,
2315        )
2316
2317    def select(
2318        self,
2319        *expressions: ExpOrStr,
2320        append: bool = True,
2321        dialect: DialectType = None,
2322        copy: bool = True,
2323        **opts,
2324    ) -> Select:
2325        """
2326        Append to or set the SELECT expressions.
2327
2328        Example:
2329            >>> Select().select("x", "y").sql()
2330            'SELECT x, y'
2331
2332        Args:
2333            *expressions: the SQL code strings to parse.
2334                If an `Expression` instance is passed, it will be used as-is.
2335            append: if `True`, add to any existing expressions.
2336                Otherwise, this resets the expressions.
2337            dialect: the dialect used to parse the input expressions.
2338            copy: if `False`, modify this expression instance in-place.
2339            opts: other options to use to parse the input expressions.
2340
2341        Returns:
2342            Select: the modified expression.
2343        """
2344        return _apply_list_builder(
2345            *expressions,
2346            instance=self,
2347            arg="expressions",
2348            append=append,
2349            dialect=dialect,
2350            copy=copy,
2351            **opts,
2352        )
2353
2354    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2355        """
2356        Append to or set the LATERAL expressions.
2357
2358        Example:
2359            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2360            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2361
2362        Args:
2363            *expressions (str | Expression): the SQL code strings to parse.
2364                If an `Expression` instance is passed, it will be used as-is.
2365            append (bool): if `True`, add to any existing expressions.
2366                Otherwise, this resets the expressions.
2367            dialect (str): the dialect used to parse the input expressions.
2368            copy (bool): if `False`, modify this expression instance in-place.
2369            opts (kwargs): other options to use to parse the input expressions.
2370
2371        Returns:
2372            Select: the modified expression.
2373        """
2374        return _apply_list_builder(
2375            *expressions,
2376            instance=self,
2377            arg="laterals",
2378            append=append,
2379            into=Lateral,
2380            prefix="LATERAL VIEW",
2381            dialect=dialect,
2382            copy=copy,
2383            **opts,
2384        )
2385
2386    def join(
2387        self,
2388        expression,
2389        on=None,
2390        using=None,
2391        append=True,
2392        join_type=None,
2393        join_alias=None,
2394        dialect=None,
2395        copy=True,
2396        **opts,
2397    ) -> Select:
2398        """
2399        Append to or set the JOIN expressions.
2400
2401        Example:
2402            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2403            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2404
2405            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2406            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2407
2408            Use `join_type` to change the type of join:
2409
2410            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2411            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2412
2413        Args:
2414            expression (str | Expression): the SQL code string to parse.
2415                If an `Expression` instance is passed, it will be used as-is.
2416            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2417                If an `Expression` instance is passed, it will be used as-is.
2418            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2419                If an `Expression` instance is passed, it will be used as-is.
2420            append (bool): if `True`, add to any existing expressions.
2421                Otherwise, this resets the expressions.
2422            join_type (str): If set, alter the parsed join type
2423            dialect (str): the dialect used to parse the input expressions.
2424            copy (bool): if `False`, modify this expression instance in-place.
2425            opts (kwargs): other options to use to parse the input expressions.
2426
2427        Returns:
2428            Select: the modified expression.
2429        """
2430        parse_args = {"dialect": dialect, **opts}
2431
2432        try:
2433            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2434        except ParseError:
2435            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2436
2437        join = expression if isinstance(expression, Join) else Join(this=expression)
2438
2439        if isinstance(join.this, Select):
2440            join.this.replace(join.this.subquery())
2441
2442        if join_type:
2443            natural: t.Optional[Token]
2444            side: t.Optional[Token]
2445            kind: t.Optional[Token]
2446
2447            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2448
2449            if natural:
2450                join.set("natural", True)
2451            if side:
2452                join.set("side", side.text)
2453            if kind:
2454                join.set("kind", kind.text)
2455
2456        if on:
2457            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2458            join.set("on", on)
2459
2460        if using:
2461            join = _apply_list_builder(
2462                *ensure_collection(using),
2463                instance=join,
2464                arg="using",
2465                append=append,
2466                copy=copy,
2467                **opts,
2468            )
2469
2470        if join_alias:
2471            join.set("this", alias_(join.this, join_alias, table=True))
2472        return _apply_list_builder(
2473            join,
2474            instance=self,
2475            arg="joins",
2476            append=append,
2477            copy=copy,
2478            **opts,
2479        )
2480
2481    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2482        """
2483        Append to or set the WHERE expressions.
2484
2485        Example:
2486            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2487            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2488
2489        Args:
2490            *expressions (str | Expression): the SQL code strings to parse.
2491                If an `Expression` instance is passed, it will be used as-is.
2492                Multiple expressions are combined with an AND operator.
2493            append (bool): if `True`, AND the new expressions to any existing expression.
2494                Otherwise, this resets the expression.
2495            dialect (str): the dialect used to parse the input expressions.
2496            copy (bool): if `False`, modify this expression instance in-place.
2497            opts (kwargs): other options to use to parse the input expressions.
2498
2499        Returns:
2500            Select: the modified expression.
2501        """
2502        return _apply_conjunction_builder(
2503            *expressions,
2504            instance=self,
2505            arg="where",
2506            append=append,
2507            into=Where,
2508            dialect=dialect,
2509            copy=copy,
2510            **opts,
2511        )
2512
2513    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2514        """
2515        Append to or set the HAVING expressions.
2516
2517        Example:
2518            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2519            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2520
2521        Args:
2522            *expressions (str | Expression): the SQL code strings to parse.
2523                If an `Expression` instance is passed, it will be used as-is.
2524                Multiple expressions are combined with an AND operator.
2525            append (bool): if `True`, AND the new expressions to any existing expression.
2526                Otherwise, this resets the expression.
2527            dialect (str): the dialect used to parse the input expressions.
2528            copy (bool): if `False`, modify this expression instance in-place.
2529            opts (kwargs): other options to use to parse the input expressions.
2530
2531        Returns:
2532            Select: the modified expression.
2533        """
2534        return _apply_conjunction_builder(
2535            *expressions,
2536            instance=self,
2537            arg="having",
2538            append=append,
2539            into=Having,
2540            dialect=dialect,
2541            copy=copy,
2542            **opts,
2543        )
2544
2545    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2546        return _apply_list_builder(
2547            *expressions,
2548            instance=self,
2549            arg="windows",
2550            append=append,
2551            into=Window,
2552            dialect=dialect,
2553            copy=copy,
2554            **opts,
2555        )
2556
2557    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2558        return _apply_conjunction_builder(
2559            *expressions,
2560            instance=self,
2561            arg="qualify",
2562            append=append,
2563            into=Qualify,
2564            dialect=dialect,
2565            copy=copy,
2566            **opts,
2567        )
2568
2569    def distinct(self, distinct=True, copy=True) -> Select:
2570        """
2571        Set the OFFSET expression.
2572
2573        Example:
2574            >>> Select().from_("tbl").select("x").distinct().sql()
2575            'SELECT DISTINCT x FROM tbl'
2576
2577        Args:
2578            distinct (bool): whether the Select should be distinct
2579            copy (bool): if `False`, modify this expression instance in-place.
2580
2581        Returns:
2582            Select: the modified expression.
2583        """
2584        instance = _maybe_copy(self, copy)
2585        instance.set("distinct", Distinct() if distinct else None)
2586        return instance
2587
2588    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2589        """
2590        Convert this expression to a CREATE TABLE AS statement.
2591
2592        Example:
2593            >>> Select().select("*").from_("tbl").ctas("x").sql()
2594            'CREATE TABLE x AS SELECT * FROM tbl'
2595
2596        Args:
2597            table (str | Expression): the SQL code string to parse as the table name.
2598                If another `Expression` instance is passed, it will be used as-is.
2599            properties (dict): an optional mapping of table properties
2600            dialect (str): the dialect used to parse the input table.
2601            copy (bool): if `False`, modify this expression instance in-place.
2602            opts (kwargs): other options to use to parse the input table.
2603
2604        Returns:
2605            Create: the CREATE TABLE AS expression
2606        """
2607        instance = _maybe_copy(self, copy)
2608        table_expression = maybe_parse(
2609            table,
2610            into=Table,
2611            dialect=dialect,
2612            **opts,
2613        )
2614        properties_expression = None
2615        if properties:
2616            properties_expression = Properties.from_dict(properties)
2617
2618        return Create(
2619            this=table_expression,
2620            kind="table",
2621            expression=instance,
2622            properties=properties_expression,
2623        )
2624
2625    def lock(self, update: bool = True, copy: bool = True) -> Select:
2626        """
2627        Set the locking read mode for this expression.
2628
2629        Examples:
2630            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2631            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2632
2633            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2634            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2635
2636        Args:
2637            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2638            copy: if `False`, modify this expression instance in-place.
2639
2640        Returns:
2641            The modified expression.
2642        """
2643
2644        inst = _maybe_copy(self, copy)
2645        inst.set("lock", Lock(update=update))
2646
2647        return inst
2648
2649    @property
2650    def named_selects(self) -> t.List[str]:
2651        return [e.output_name for e in self.expressions if e.alias_or_name]
2652
2653    @property
2654    def is_star(self) -> bool:
2655        return any(expression.is_star for expression in self.expressions)
2656
2657    @property
2658    def selects(self) -> t.List[Expression]:
2659        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2087    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2088        """
2089        Set the FROM expression.
2090
2091        Example:
2092            >>> Select().from_("tbl").select("x").sql()
2093            'SELECT x FROM tbl'
2094
2095        Args:
2096            *expressions (str | Expression): the SQL code strings to parse.
2097                If a `From` instance is passed, this is used as-is.
2098                If another `Expression` instance is passed, it will be wrapped in a `From`.
2099            append (bool): if `True`, add to any existing expressions.
2100                Otherwise, this flattens all the `From` expression into a single expression.
2101            dialect (str): the dialect used to parse the input expression.
2102            copy (bool): if `False`, modify this expression instance in-place.
2103            opts (kwargs): other options to use to parse the input expressions.
2104
2105        Returns:
2106            Select: the modified expression.
2107        """
2108        return _apply_child_list_builder(
2109            *expressions,
2110            instance=self,
2111            arg="from",
2112            append=append,
2113            copy=copy,
2114            prefix="FROM",
2115            into=From,
2116            dialect=dialect,
2117            **opts,
2118        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2120    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2121        """
2122        Set the GROUP BY expression.
2123
2124        Example:
2125            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2126            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2127
2128        Args:
2129            *expressions (str | Expression): the SQL code strings to parse.
2130                If a `Group` instance is passed, this is used as-is.
2131                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2132                If nothing is passed in then a group by is not applied to the expression
2133            append (bool): if `True`, add to any existing expressions.
2134                Otherwise, this flattens all the `Group` expression into a single expression.
2135            dialect (str): the dialect used to parse the input expression.
2136            copy (bool): if `False`, modify this expression instance in-place.
2137            opts (kwargs): other options to use to parse the input expressions.
2138
2139        Returns:
2140            Select: the modified expression.
2141        """
2142        if not expressions:
2143            return self if not copy else self.copy()
2144        return _apply_child_list_builder(
2145            *expressions,
2146            instance=self,
2147            arg="group",
2148            append=append,
2149            copy=copy,
2150            prefix="GROUP BY",
2151            into=Group,
2152            dialect=dialect,
2153            **opts,
2154        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2156    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2157        """
2158        Set the ORDER BY expression.
2159
2160        Example:
2161            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2162            'SELECT x FROM tbl ORDER BY x DESC'
2163
2164        Args:
2165            *expressions (str | Expression): the SQL code strings to parse.
2166                If a `Group` instance is passed, this is used as-is.
2167                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2168            append (bool): if `True`, add to any existing expressions.
2169                Otherwise, this flattens all the `Order` expression into a single expression.
2170            dialect (str): the dialect used to parse the input expression.
2171            copy (bool): if `False`, modify this expression instance in-place.
2172            opts (kwargs): other options to use to parse the input expressions.
2173
2174        Returns:
2175            Select: the modified expression.
2176        """
2177        return _apply_child_list_builder(
2178            *expressions,
2179            instance=self,
2180            arg="order",
2181            append=append,
2182            copy=copy,
2183            prefix="ORDER BY",
2184            into=Order,
2185            dialect=dialect,
2186            **opts,
2187        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2189    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2190        """
2191        Set the SORT BY expression.
2192
2193        Example:
2194            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2195            'SELECT x FROM tbl SORT BY x DESC'
2196
2197        Args:
2198            *expressions (str | Expression): the SQL code strings to parse.
2199                If a `Group` instance is passed, this is used as-is.
2200                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2201            append (bool): if `True`, add to any existing expressions.
2202                Otherwise, this flattens all the `Order` expression into a single expression.
2203            dialect (str): the dialect used to parse the input expression.
2204            copy (bool): if `False`, modify this expression instance in-place.
2205            opts (kwargs): other options to use to parse the input expressions.
2206
2207        Returns:
2208            Select: the modified expression.
2209        """
2210        return _apply_child_list_builder(
2211            *expressions,
2212            instance=self,
2213            arg="sort",
2214            append=append,
2215            copy=copy,
2216            prefix="SORT BY",
2217            into=Sort,
2218            dialect=dialect,
2219            **opts,
2220        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2222    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2223        """
2224        Set the CLUSTER BY expression.
2225
2226        Example:
2227            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2228            'SELECT x FROM tbl CLUSTER BY x DESC'
2229
2230        Args:
2231            *expressions (str | Expression): the SQL code strings to parse.
2232                If a `Group` instance is passed, this is used as-is.
2233                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2234            append (bool): if `True`, add to any existing expressions.
2235                Otherwise, this flattens all the `Order` expression into a single expression.
2236            dialect (str): the dialect used to parse the input expression.
2237            copy (bool): if `False`, modify this expression instance in-place.
2238            opts (kwargs): other options to use to parse the input expressions.
2239
2240        Returns:
2241            Select: the modified expression.
2242        """
2243        return _apply_child_list_builder(
2244            *expressions,
2245            instance=self,
2246            arg="cluster",
2247            append=append,
2248            copy=copy,
2249            prefix="CLUSTER BY",
2250            into=Cluster,
2251            dialect=dialect,
2252            **opts,
2253        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2255    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2256        """
2257        Set the LIMIT expression.
2258
2259        Example:
2260            >>> Select().from_("tbl").select("x").limit(10).sql()
2261            'SELECT x FROM tbl LIMIT 10'
2262
2263        Args:
2264            expression (str | int | Expression): the SQL code string to parse.
2265                This can also be an integer.
2266                If a `Limit` instance is passed, this is used as-is.
2267                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2268            dialect (str): the dialect used to parse the input expression.
2269            copy (bool): if `False`, modify this expression instance in-place.
2270            opts (kwargs): other options to use to parse the input expressions.
2271
2272        Returns:
2273            Select: the modified expression.
2274        """
2275        return _apply_builder(
2276            expression=expression,
2277            instance=self,
2278            arg="limit",
2279            into=Limit,
2280            prefix="LIMIT",
2281            dialect=dialect,
2282            copy=copy,
2283            **opts,
2284        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2286    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2287        """
2288        Set the OFFSET expression.
2289
2290        Example:
2291            >>> Select().from_("tbl").select("x").offset(10).sql()
2292            'SELECT x FROM tbl OFFSET 10'
2293
2294        Args:
2295            expression (str | int | Expression): the SQL code string to parse.
2296                This can also be an integer.
2297                If a `Offset` instance is passed, this is used as-is.
2298                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2299            dialect (str): the dialect used to parse the input expression.
2300            copy (bool): if `False`, modify this expression instance in-place.
2301            opts (kwargs): other options to use to parse the input expressions.
2302
2303        Returns:
2304            Select: the modified expression.
2305        """
2306        return _apply_builder(
2307            expression=expression,
2308            instance=self,
2309            arg="offset",
2310            into=Offset,
2311            prefix="OFFSET",
2312            dialect=dialect,
2313            copy=copy,
2314            **opts,
2315        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2317    def select(
2318        self,
2319        *expressions: ExpOrStr,
2320        append: bool = True,
2321        dialect: DialectType = None,
2322        copy: bool = True,
2323        **opts,
2324    ) -> Select:
2325        """
2326        Append to or set the SELECT expressions.
2327
2328        Example:
2329            >>> Select().select("x", "y").sql()
2330            'SELECT x, y'
2331
2332        Args:
2333            *expressions: the SQL code strings to parse.
2334                If an `Expression` instance is passed, it will be used as-is.
2335            append: if `True`, add to any existing expressions.
2336                Otherwise, this resets the expressions.
2337            dialect: the dialect used to parse the input expressions.
2338            copy: if `False`, modify this expression instance in-place.
2339            opts: other options to use to parse the input expressions.
2340
2341        Returns:
2342            Select: the modified expression.
2343        """
2344        return _apply_list_builder(
2345            *expressions,
2346            instance=self,
2347            arg="expressions",
2348            append=append,
2349            dialect=dialect,
2350            copy=copy,
2351            **opts,
2352        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2354    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2355        """
2356        Append to or set the LATERAL expressions.
2357
2358        Example:
2359            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2360            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2361
2362        Args:
2363            *expressions (str | Expression): the SQL code strings to parse.
2364                If an `Expression` instance is passed, it will be used as-is.
2365            append (bool): if `True`, add to any existing expressions.
2366                Otherwise, this resets the expressions.
2367            dialect (str): the dialect used to parse the input expressions.
2368            copy (bool): if `False`, modify this expression instance in-place.
2369            opts (kwargs): other options to use to parse the input expressions.
2370
2371        Returns:
2372            Select: the modified expression.
2373        """
2374        return _apply_list_builder(
2375            *expressions,
2376            instance=self,
2377            arg="laterals",
2378            append=append,
2379            into=Lateral,
2380            prefix="LATERAL VIEW",
2381            dialect=dialect,
2382            copy=copy,
2383            **opts,
2384        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2386    def join(
2387        self,
2388        expression,
2389        on=None,
2390        using=None,
2391        append=True,
2392        join_type=None,
2393        join_alias=None,
2394        dialect=None,
2395        copy=True,
2396        **opts,
2397    ) -> Select:
2398        """
2399        Append to or set the JOIN expressions.
2400
2401        Example:
2402            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2403            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2404
2405            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2406            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2407
2408            Use `join_type` to change the type of join:
2409
2410            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2411            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2412
2413        Args:
2414            expression (str | Expression): the SQL code string to parse.
2415                If an `Expression` instance is passed, it will be used as-is.
2416            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2417                If an `Expression` instance is passed, it will be used as-is.
2418            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2419                If an `Expression` instance is passed, it will be used as-is.
2420            append (bool): if `True`, add to any existing expressions.
2421                Otherwise, this resets the expressions.
2422            join_type (str): If set, alter the parsed join type
2423            dialect (str): the dialect used to parse the input expressions.
2424            copy (bool): if `False`, modify this expression instance in-place.
2425            opts (kwargs): other options to use to parse the input expressions.
2426
2427        Returns:
2428            Select: the modified expression.
2429        """
2430        parse_args = {"dialect": dialect, **opts}
2431
2432        try:
2433            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2434        except ParseError:
2435            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2436
2437        join = expression if isinstance(expression, Join) else Join(this=expression)
2438
2439        if isinstance(join.this, Select):
2440            join.this.replace(join.this.subquery())
2441
2442        if join_type:
2443            natural: t.Optional[Token]
2444            side: t.Optional[Token]
2445            kind: t.Optional[Token]
2446
2447            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2448
2449            if natural:
2450                join.set("natural", True)
2451            if side:
2452                join.set("side", side.text)
2453            if kind:
2454                join.set("kind", kind.text)
2455
2456        if on:
2457            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2458            join.set("on", on)
2459
2460        if using:
2461            join = _apply_list_builder(
2462                *ensure_collection(using),
2463                instance=join,
2464                arg="using",
2465                append=append,
2466                copy=copy,
2467                **opts,
2468            )
2469
2470        if join_alias:
2471            join.set("this", alias_(join.this, join_alias, table=True))
2472        return _apply_list_builder(
2473            join,
2474            instance=self,
2475            arg="joins",
2476            append=append,
2477            copy=copy,
2478            **opts,
2479        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2481    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2482        """
2483        Append to or set the WHERE expressions.
2484
2485        Example:
2486            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2487            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2488
2489        Args:
2490            *expressions (str | Expression): the SQL code strings to parse.
2491                If an `Expression` instance is passed, it will be used as-is.
2492                Multiple expressions are combined with an AND operator.
2493            append (bool): if `True`, AND the new expressions to any existing expression.
2494                Otherwise, this resets the expression.
2495            dialect (str): the dialect used to parse the input expressions.
2496            copy (bool): if `False`, modify this expression instance in-place.
2497            opts (kwargs): other options to use to parse the input expressions.
2498
2499        Returns:
2500            Select: the modified expression.
2501        """
2502        return _apply_conjunction_builder(
2503            *expressions,
2504            instance=self,
2505            arg="where",
2506            append=append,
2507            into=Where,
2508            dialect=dialect,
2509            copy=copy,
2510            **opts,
2511        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2513    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2514        """
2515        Append to or set the HAVING expressions.
2516
2517        Example:
2518            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2519            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2520
2521        Args:
2522            *expressions (str | Expression): the SQL code strings to parse.
2523                If an `Expression` instance is passed, it will be used as-is.
2524                Multiple expressions are combined with an AND operator.
2525            append (bool): if `True`, AND the new expressions to any existing expression.
2526                Otherwise, this resets the expression.
2527            dialect (str): the dialect used to parse the input expressions.
2528            copy (bool): if `False`, modify this expression instance in-place.
2529            opts (kwargs): other options to use to parse the input expressions.
2530
2531        Returns:
2532            Select: the modified expression.
2533        """
2534        return _apply_conjunction_builder(
2535            *expressions,
2536            instance=self,
2537            arg="having",
2538            append=append,
2539            into=Having,
2540            dialect=dialect,
2541            copy=copy,
2542            **opts,
2543        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2545    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2546        return _apply_list_builder(
2547            *expressions,
2548            instance=self,
2549            arg="windows",
2550            append=append,
2551            into=Window,
2552            dialect=dialect,
2553            copy=copy,
2554            **opts,
2555        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2557    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2558        return _apply_conjunction_builder(
2559            *expressions,
2560            instance=self,
2561            arg="qualify",
2562            append=append,
2563            into=Qualify,
2564            dialect=dialect,
2565            copy=copy,
2566            **opts,
2567        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2569    def distinct(self, distinct=True, copy=True) -> Select:
2570        """
2571        Set the OFFSET expression.
2572
2573        Example:
2574            >>> Select().from_("tbl").select("x").distinct().sql()
2575            'SELECT DISTINCT x FROM tbl'
2576
2577        Args:
2578            distinct (bool): whether the Select should be distinct
2579            copy (bool): if `False`, modify this expression instance in-place.
2580
2581        Returns:
2582            Select: the modified expression.
2583        """
2584        instance = _maybe_copy(self, copy)
2585        instance.set("distinct", Distinct() if distinct else None)
2586        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • distinct (bool): whether the Select should be distinct
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2588    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2589        """
2590        Convert this expression to a CREATE TABLE AS statement.
2591
2592        Example:
2593            >>> Select().select("*").from_("tbl").ctas("x").sql()
2594            'CREATE TABLE x AS SELECT * FROM tbl'
2595
2596        Args:
2597            table (str | Expression): the SQL code string to parse as the table name.
2598                If another `Expression` instance is passed, it will be used as-is.
2599            properties (dict): an optional mapping of table properties
2600            dialect (str): the dialect used to parse the input table.
2601            copy (bool): if `False`, modify this expression instance in-place.
2602            opts (kwargs): other options to use to parse the input table.
2603
2604        Returns:
2605            Create: the CREATE TABLE AS expression
2606        """
2607        instance = _maybe_copy(self, copy)
2608        table_expression = maybe_parse(
2609            table,
2610            into=Table,
2611            dialect=dialect,
2612            **opts,
2613        )
2614        properties_expression = None
2615        if properties:
2616            properties_expression = Properties.from_dict(properties)
2617
2618        return Create(
2619            this=table_expression,
2620            kind="table",
2621            expression=instance,
2622            properties=properties_expression,
2623        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2625    def lock(self, update: bool = True, copy: bool = True) -> Select:
2626        """
2627        Set the locking read mode for this expression.
2628
2629        Examples:
2630            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2631            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2632
2633            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2634            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2635
2636        Args:
2637            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2638            copy: if `False`, modify this expression instance in-place.
2639
2640        Returns:
2641            The modified expression.
2642        """
2643
2644        inst = _maybe_copy(self, copy)
2645        inst.set("lock", Lock(update=update))
2646
2647        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2662class Subquery(DerivedTable, Unionable):
2663    arg_types = {
2664        "this": True,
2665        "alias": False,
2666        "with": False,
2667        **QUERY_MODIFIERS,
2668    }
2669
2670    def unnest(self):
2671        """
2672        Returns the first non subquery.
2673        """
2674        expression = self
2675        while isinstance(expression, Subquery):
2676            expression = expression.this
2677        return expression
2678
2679    @property
2680    def is_star(self) -> bool:
2681        return self.this.is_star
2682
2683    @property
2684    def output_name(self):
2685        return self.alias
def unnest(self):
2670    def unnest(self):
2671        """
2672        Returns the first non subquery.
2673        """
2674        expression = self
2675        while isinstance(expression, Subquery):
2676            expression = expression.this
2677        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2688class TableSample(Expression):
2689    arg_types = {
2690        "this": False,
2691        "method": False,
2692        "bucket_numerator": False,
2693        "bucket_denominator": False,
2694        "bucket_field": False,
2695        "percent": False,
2696        "rows": False,
2697        "size": False,
2698        "seed": False,
2699        "kind": False,
2700    }
class Tag(Expression):
2703class Tag(Expression):
2704    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2705
2706    arg_types = {
2707        "this": False,
2708        "prefix": False,
2709        "postfix": False,
2710    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2713class Pivot(Expression):
2714    arg_types = {
2715        "this": False,
2716        "alias": False,
2717        "expressions": True,
2718        "field": True,
2719        "unpivot": True,
2720    }
class Window(Expression):
2723class Window(Expression):
2724    arg_types = {
2725        "this": True,
2726        "partition_by": False,
2727        "order": False,
2728        "spec": False,
2729        "alias": False,
2730    }
class WindowSpec(Expression):
2733class WindowSpec(Expression):
2734    arg_types = {
2735        "kind": False,
2736        "start": False,
2737        "start_side": False,
2738        "end": False,
2739        "end_side": False,
2740    }
class Where(Expression):
2743class Where(Expression):
2744    pass
class Star(Expression):
2747class Star(Expression):
2748    arg_types = {"except": False, "replace": False}
2749
2750    @property
2751    def name(self) -> str:
2752        return "*"
2753
2754    @property
2755    def output_name(self):
2756        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2759class Parameter(Expression):
2760    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2763class SessionParameter(Expression):
2764    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2767class Placeholder(Expression):
2768    arg_types = {"this": False}
class Null(Condition):
2771class Null(Condition):
2772    arg_types: t.Dict[str, t.Any] = {}
2773
2774    @property
2775    def name(self) -> str:
2776        return "NULL"
class Boolean(Condition):
2779class Boolean(Condition):
2780    pass
class DataType(Expression):
2783class DataType(Expression):
2784    arg_types = {
2785        "this": True,
2786        "expressions": False,
2787        "nested": False,
2788        "values": False,
2789        "prefix": False,
2790    }
2791
2792    class Type(AutoName):
2793        CHAR = auto()
2794        NCHAR = auto()
2795        VARCHAR = auto()
2796        NVARCHAR = auto()
2797        TEXT = auto()
2798        MEDIUMTEXT = auto()
2799        LONGTEXT = auto()
2800        MEDIUMBLOB = auto()
2801        LONGBLOB = auto()
2802        BINARY = auto()
2803        VARBINARY = auto()
2804        INT = auto()
2805        UINT = auto()
2806        TINYINT = auto()
2807        UTINYINT = auto()
2808        SMALLINT = auto()
2809        USMALLINT = auto()
2810        BIGINT = auto()
2811        UBIGINT = auto()
2812        FLOAT = auto()
2813        DOUBLE = auto()
2814        DECIMAL = auto()
2815        BIT = auto()
2816        BOOLEAN = auto()
2817        JSON = auto()
2818        JSONB = auto()
2819        INTERVAL = auto()
2820        TIME = auto()
2821        TIMESTAMP = auto()
2822        TIMESTAMPTZ = auto()
2823        TIMESTAMPLTZ = auto()
2824        DATE = auto()
2825        DATETIME = auto()
2826        ARRAY = auto()
2827        MAP = auto()
2828        UUID = auto()
2829        GEOGRAPHY = auto()
2830        GEOMETRY = auto()
2831        STRUCT = auto()
2832        NULLABLE = auto()
2833        HLLSKETCH = auto()
2834        HSTORE = auto()
2835        SUPER = auto()
2836        SERIAL = auto()
2837        SMALLSERIAL = auto()
2838        BIGSERIAL = auto()
2839        XML = auto()
2840        UNIQUEIDENTIFIER = auto()
2841        MONEY = auto()
2842        SMALLMONEY = auto()
2843        ROWVERSION = auto()
2844        IMAGE = auto()
2845        VARIANT = auto()
2846        OBJECT = auto()
2847        INET = auto()
2848        NULL = auto()
2849        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2850
2851    TEXT_TYPES = {
2852        Type.CHAR,
2853        Type.NCHAR,
2854        Type.VARCHAR,
2855        Type.NVARCHAR,
2856        Type.TEXT,
2857    }
2858
2859    INTEGER_TYPES = {
2860        Type.INT,
2861        Type.TINYINT,
2862        Type.SMALLINT,
2863        Type.BIGINT,
2864    }
2865
2866    FLOAT_TYPES = {
2867        Type.FLOAT,
2868        Type.DOUBLE,
2869    }
2870
2871    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2872
2873    TEMPORAL_TYPES = {
2874        Type.TIMESTAMP,
2875        Type.TIMESTAMPTZ,
2876        Type.TIMESTAMPLTZ,
2877        Type.DATE,
2878        Type.DATETIME,
2879    }
2880
2881    @classmethod
2882    def build(
2883        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2884    ) -> DataType:
2885        from sqlglot import parse_one
2886
2887        if isinstance(dtype, str):
2888            if dtype.upper() in cls.Type.__members__:
2889                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2890            else:
2891                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2892            if data_type_exp is None:
2893                raise ValueError(f"Unparsable data type value: {dtype}")
2894        elif isinstance(dtype, DataType.Type):
2895            data_type_exp = DataType(this=dtype)
2896        elif isinstance(dtype, DataType):
2897            return dtype
2898        else:
2899            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2900        return DataType(**{**data_type_exp.args, **kwargs})
2901
2902    def is_type(self, dtype: DataType.Type) -> bool:
2903        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2881    @classmethod
2882    def build(
2883        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2884    ) -> DataType:
2885        from sqlglot import parse_one
2886
2887        if isinstance(dtype, str):
2888            if dtype.upper() in cls.Type.__members__:
2889                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2890            else:
2891                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2892            if data_type_exp is None:
2893                raise ValueError(f"Unparsable data type value: {dtype}")
2894        elif isinstance(dtype, DataType.Type):
2895            data_type_exp = DataType(this=dtype)
2896        elif isinstance(dtype, DataType):
2897            return dtype
2898        else:
2899            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2900        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2902    def is_type(self, dtype: DataType.Type) -> bool:
2903        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2792    class Type(AutoName):
2793        CHAR = auto()
2794        NCHAR = auto()
2795        VARCHAR = auto()
2796        NVARCHAR = auto()
2797        TEXT = auto()
2798        MEDIUMTEXT = auto()
2799        LONGTEXT = auto()
2800        MEDIUMBLOB = auto()
2801        LONGBLOB = auto()
2802        BINARY = auto()
2803        VARBINARY = auto()
2804        INT = auto()
2805        UINT = auto()
2806        TINYINT = auto()
2807        UTINYINT = auto()
2808        SMALLINT = auto()
2809        USMALLINT = auto()
2810        BIGINT = auto()
2811        UBIGINT = auto()
2812        FLOAT = auto()
2813        DOUBLE = auto()
2814        DECIMAL = auto()
2815        BIT = auto()
2816        BOOLEAN = auto()
2817        JSON = auto()
2818        JSONB = auto()
2819        INTERVAL = auto()
2820        TIME = auto()
2821        TIMESTAMP = auto()
2822        TIMESTAMPTZ = auto()
2823        TIMESTAMPLTZ = auto()
2824        DATE = auto()
2825        DATETIME = auto()
2826        ARRAY = auto()
2827        MAP = auto()
2828        UUID = auto()
2829        GEOGRAPHY = auto()
2830        GEOMETRY = auto()
2831        STRUCT = auto()
2832        NULLABLE = auto()
2833        HLLSKETCH = auto()
2834        HSTORE = auto()
2835        SUPER = auto()
2836        SERIAL = auto()
2837        SMALLSERIAL = auto()
2838        BIGSERIAL = auto()
2839        XML = auto()
2840        UNIQUEIDENTIFIER = auto()
2841        MONEY = auto()
2842        SMALLMONEY = auto()
2843        ROWVERSION = auto()
2844        IMAGE = auto()
2845        VARIANT = auto()
2846        OBJECT = auto()
2847        INET = auto()
2848        NULL = auto()
2849        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2907class PseudoType(Expression):
2908    pass
class StructKwarg(Expression):
2911class StructKwarg(Expression):
2912    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2916class SubqueryPredicate(Predicate):
2917    pass
class All(SubqueryPredicate):
2920class All(SubqueryPredicate):
2921    pass
class Any(SubqueryPredicate):
2924class Any(SubqueryPredicate):
2925    pass
class Exists(SubqueryPredicate):
2928class Exists(SubqueryPredicate):
2929    pass
class Command(Expression):
2934class Command(Expression):
2935    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2938class Transaction(Expression):
2939    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2942class Commit(Expression):
2943    arg_types = {"chain": False}
class Rollback(Expression):
2946class Rollback(Expression):
2947    arg_types = {"savepoint": False}
class AlterTable(Expression):
2950class AlterTable(Expression):
2951    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2954class AddConstraint(Expression):
2955    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2958class DropPartition(Expression):
2959    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2963class Binary(Expression):
2964    arg_types = {"this": True, "expression": True}
2965
2966    @property
2967    def left(self):
2968        return self.this
2969
2970    @property
2971    def right(self):
2972        return self.expression
class Add(Binary):
2975class Add(Binary):
2976    pass
class Connector(Binary, Condition):
2979class Connector(Binary, Condition):
2980    pass
class And(Connector):
2983class And(Connector):
2984    pass
class Or(Connector):
2987class Or(Connector):
2988    pass
class BitwiseAnd(Binary):
2991class BitwiseAnd(Binary):
2992    pass
class BitwiseLeftShift(Binary):
2995class BitwiseLeftShift(Binary):
2996    pass
class BitwiseOr(Binary):
2999class BitwiseOr(Binary):
3000    pass
class BitwiseRightShift(Binary):
3003class BitwiseRightShift(Binary):
3004    pass
class BitwiseXor(Binary):
3007class BitwiseXor(Binary):
3008    pass
class Div(Binary):
3011class Div(Binary):
3012    pass
class Overlaps(Binary):
3015class Overlaps(Binary):
3016    pass
class Dot(Binary):
3019class Dot(Binary):
3020    @property
3021    def name(self) -> str:
3022        return self.expression.name
3023
3024    @classmethod
3025    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3026        """Build a Dot object with a sequence of expressions."""
3027        if len(expressions) < 2:
3028            raise ValueError(f"Dot requires >= 2 expressions.")
3029
3030        a, b, *expressions = expressions
3031        dot = Dot(this=a, expression=b)
3032
3033        for expression in expressions:
3034            dot = Dot(this=dot, expression=expression)
3035
3036        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3024    @classmethod
3025    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3026        """Build a Dot object with a sequence of expressions."""
3027        if len(expressions) < 2:
3028            raise ValueError(f"Dot requires >= 2 expressions.")
3029
3030        a, b, *expressions = expressions
3031        dot = Dot(this=a, expression=b)
3032
3033        for expression in expressions:
3034            dot = Dot(this=dot, expression=expression)
3035
3036        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3039class DPipe(Binary):
3040    pass
class EQ(Binary, Predicate):
3043class EQ(Binary, Predicate):
3044    pass
class NullSafeEQ(Binary, Predicate):
3047class NullSafeEQ(Binary, Predicate):
3048    pass
class NullSafeNEQ(Binary, Predicate):
3051class NullSafeNEQ(Binary, Predicate):
3052    pass
class Distance(Binary):
3055class Distance(Binary):
3056    pass
class Escape(Binary):
3059class Escape(Binary):
3060    pass
class Glob(Binary, Predicate):
3063class Glob(Binary, Predicate):
3064    pass
class GT(Binary, Predicate):
3067class GT(Binary, Predicate):
3068    pass
class GTE(Binary, Predicate):
3071class GTE(Binary, Predicate):
3072    pass
class ILike(Binary, Predicate):
3075class ILike(Binary, Predicate):
3076    pass
class ILikeAny(Binary, Predicate):
3079class ILikeAny(Binary, Predicate):
3080    pass
class IntDiv(Binary):
3083class IntDiv(Binary):
3084    pass
class Is(Binary, Predicate):
3087class Is(Binary, Predicate):
3088    pass
class Kwarg(Binary):
3091class Kwarg(Binary):
3092    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3095class Like(Binary, Predicate):
3096    pass
class LikeAny(Binary, Predicate):
3099class LikeAny(Binary, Predicate):
3100    pass
class LT(Binary, Predicate):
3103class LT(Binary, Predicate):
3104    pass
class LTE(Binary, Predicate):
3107class LTE(Binary, Predicate):
3108    pass
class Mod(Binary):
3111class Mod(Binary):
3112    pass
class Mul(Binary):
3115class Mul(Binary):
3116    pass
class NEQ(Binary, Predicate):
3119class NEQ(Binary, Predicate):
3120    pass
class SimilarTo(Binary, Predicate):
3123class SimilarTo(Binary, Predicate):
3124    pass
class Slice(Binary):
3127class Slice(Binary):
3128    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3131class Sub(Binary):
3132    pass
class ArrayOverlaps(Binary):
3135class ArrayOverlaps(Binary):
3136    pass
class Unary(Expression):
3141class Unary(Expression):
3142    pass
class BitwiseNot(Unary):
3145class BitwiseNot(Unary):
3146    pass
class Not(Unary, Condition):
3149class Not(Unary, Condition):
3150    pass
class Paren(Unary, Condition):
3153class Paren(Unary, Condition):
3154    arg_types = {"this": True, "with": False}
class Neg(Unary):
3157class Neg(Unary):
3158    pass
class Alias(Expression):
3162class Alias(Expression):
3163    arg_types = {"this": True, "alias": False}
3164
3165    @property
3166    def output_name(self):
3167        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3170class Aliases(Expression):
3171    arg_types = {"this": True, "expressions": True}
3172
3173    @property
3174    def aliases(self):
3175        return self.expressions
class AtTimeZone(Expression):
3178class AtTimeZone(Expression):
3179    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3182class Between(Predicate):
3183    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3186class Bracket(Condition):
3187    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3190class Distinct(Expression):
3191    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3194class In(Predicate):
3195    arg_types = {
3196        "this": True,
3197        "expressions": False,
3198        "query": False,
3199        "unnest": False,
3200        "field": False,
3201        "is_global": False,
3202    }
class TimeUnit(Expression):
3205class TimeUnit(Expression):
3206    """Automatically converts unit arg into a var."""
3207
3208    arg_types = {"unit": False}
3209
3210    def __init__(self, **args):
3211        unit = args.get("unit")
3212        if isinstance(unit, (Column, Literal)):
3213            args["unit"] = Var(this=unit.name)
3214        elif isinstance(unit, Week):
3215            unit.set("this", Var(this=unit.this.name))
3216        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3210    def __init__(self, **args):
3211        unit = args.get("unit")
3212        if isinstance(unit, (Column, Literal)):
3213            args["unit"] = Var(this=unit.name)
3214        elif isinstance(unit, Week):
3215            unit.set("this", Var(this=unit.this.name))
3216        super().__init__(**args)
class Interval(TimeUnit):
3219class Interval(TimeUnit):
3220    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3223class IgnoreNulls(Expression):
3224    pass
class RespectNulls(Expression):
3227class RespectNulls(Expression):
3228    pass
class Func(Condition):
3232class Func(Condition):
3233    """
3234    The base class for all function expressions.
3235
3236    Attributes:
3237        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3238            treated as a variable length argument and the argument's value will be stored as a list.
3239        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3240            for this function expression. These values are used to map this node to a name during parsing
3241            as well as to provide the function's name during SQL string generation. By default the SQL
3242            name is set to the expression's class name transformed to snake case.
3243    """
3244
3245    is_var_len_args = False
3246
3247    @classmethod
3248    def from_arg_list(cls, args):
3249        if cls.is_var_len_args:
3250            all_arg_keys = list(cls.arg_types)
3251            # If this function supports variable length argument treat the last argument as such.
3252            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3253            num_non_var = len(non_var_len_arg_keys)
3254
3255            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3256            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3257        else:
3258            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3259
3260        return cls(**args_dict)
3261
3262    @classmethod
3263    def sql_names(cls):
3264        if cls is Func:
3265            raise NotImplementedError(
3266                "SQL name is only supported by concrete function implementations"
3267            )
3268        if "_sql_names" not in cls.__dict__:
3269            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3270        return cls._sql_names
3271
3272    @classmethod
3273    def sql_name(cls):
3274        return cls.sql_names()[0]
3275
3276    @classmethod
3277    def default_parser_mappings(cls):
3278        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3247    @classmethod
3248    def from_arg_list(cls, args):
3249        if cls.is_var_len_args:
3250            all_arg_keys = list(cls.arg_types)
3251            # If this function supports variable length argument treat the last argument as such.
3252            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3253            num_non_var = len(non_var_len_arg_keys)
3254
3255            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3256            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3257        else:
3258            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3259
3260        return cls(**args_dict)
@classmethod
def sql_names(cls):
3262    @classmethod
3263    def sql_names(cls):
3264        if cls is Func:
3265            raise NotImplementedError(
3266                "SQL name is only supported by concrete function implementations"
3267            )
3268        if "_sql_names" not in cls.__dict__:
3269            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3270        return cls._sql_names
@classmethod
def sql_name(cls):
3272    @classmethod
3273    def sql_name(cls):
3274        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3276    @classmethod
3277    def default_parser_mappings(cls):
3278        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3281class AggFunc(Func):
3282    pass
class Abs(Func):
3285class Abs(Func):
3286    pass
class Anonymous(Func):
3289class Anonymous(Func):
3290    arg_types = {"this": True, "expressions": False}
3291    is_var_len_args = True
class Hll(AggFunc):
3296class Hll(AggFunc):
3297    arg_types = {"this": True, "expressions": False}
3298    is_var_len_args = True
class ApproxDistinct(AggFunc):
3301class ApproxDistinct(AggFunc):
3302    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3305class Array(Func):
3306    arg_types = {"expressions": False}
3307    is_var_len_args = True
class ToChar(Func):
3311class ToChar(Func):
3312    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3315class GenerateSeries(Func):
3316    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3319class ArrayAgg(AggFunc):
3320    pass
class ArrayAll(Func):
3323class ArrayAll(Func):
3324    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3327class ArrayAny(Func):
3328    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3331class ArrayConcat(Func):
3332    arg_types = {"this": True, "expressions": False}
3333    is_var_len_args = True
class ArrayContains(Binary, Func):
3336class ArrayContains(Binary, Func):
3337    pass
class ArrayContained(Binary):
3340class ArrayContained(Binary):
3341    pass
class ArrayFilter(Func):
3344class ArrayFilter(Func):
3345    arg_types = {"this": True, "expression": True}
3346    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3349class ArrayJoin(Func):
3350    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3353class ArraySize(Func):
3354    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3357class ArraySort(Func):
3358    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3361class ArraySum(Func):
3362    pass
class ArrayUnionAgg(AggFunc):
3365class ArrayUnionAgg(AggFunc):
3366    pass
class Avg(AggFunc):
3369class Avg(AggFunc):
3370    pass
class AnyValue(AggFunc):
3373class AnyValue(AggFunc):
3374    pass
class Case(Func):
3377class Case(Func):
3378    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3381class Cast(Func):
3382    arg_types = {"this": True, "to": True}
3383
3384    @property
3385    def name(self) -> str:
3386        return self.this.name
3387
3388    @property
3389    def to(self):
3390        return self.args["to"]
3391
3392    @property
3393    def output_name(self):
3394        return self.name
3395
3396    def is_type(self, dtype: DataType.Type) -> bool:
3397        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3396    def is_type(self, dtype: DataType.Type) -> bool:
3397        return self.to.is_type(dtype)
class Collate(Binary):
3400class Collate(Binary):
3401    pass
class TryCast(Cast):
3404class TryCast(Cast):
3405    pass
class Ceil(Func):
3408class Ceil(Func):
3409    arg_types = {"this": True, "decimals": False}
3410    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3413class Coalesce(Func):
3414    arg_types = {"this": True, "expressions": False}
3415    is_var_len_args = True
class Concat(Func):
3418class Concat(Func):
3419    arg_types = {"expressions": True}
3420    is_var_len_args = True
class ConcatWs(Concat):
3423class ConcatWs(Concat):
3424    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3427class Count(AggFunc):
3428    arg_types = {"this": False}
class CountIf(AggFunc):
3431class CountIf(AggFunc):
3432    pass
class CurrentDate(Func):
3435class CurrentDate(Func):
3436    arg_types = {"this": False}
class CurrentDatetime(Func):
3439class CurrentDatetime(Func):
3440    arg_types = {"this": False}
class CurrentTime(Func):
3443class CurrentTime(Func):
3444    arg_types = {"this": False}
class CurrentTimestamp(Func):
3447class CurrentTimestamp(Func):
3448    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3451class DateAdd(Func, TimeUnit):
3452    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3455class DateSub(Func, TimeUnit):
3456    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3459class DateDiff(Func, TimeUnit):
3460    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3461    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3464class DateTrunc(Func):
3465    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3468class DatetimeAdd(Func, TimeUnit):
3469    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3472class DatetimeSub(Func, TimeUnit):
3473    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3476class DatetimeDiff(Func, TimeUnit):
3477    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3480class DatetimeTrunc(Func, TimeUnit):
3481    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3484class DayOfWeek(Func):
3485    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3488class DayOfMonth(Func):
3489    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3492class DayOfYear(Func):
3493    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3496class WeekOfYear(Func):
3497    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3500class LastDateOfMonth(Func):
3501    pass
class Extract(Func):
3504class Extract(Func):
3505    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3508class TimestampAdd(Func, TimeUnit):
3509    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3512class TimestampSub(Func, TimeUnit):
3513    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3516class TimestampDiff(Func, TimeUnit):
3517    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3520class TimestampTrunc(Func, TimeUnit):
3521    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3524class TimeAdd(Func, TimeUnit):
3525    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3528class TimeSub(Func, TimeUnit):
3529    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3532class TimeDiff(Func, TimeUnit):
3533    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3536class TimeTrunc(Func, TimeUnit):
3537    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3540class DateFromParts(Func):
3541    _sql_names = ["DATEFROMPARTS"]
3542    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3545class DateStrToDate(Func):
3546    pass
class DateToDateStr(Func):
3549class DateToDateStr(Func):
3550    pass
class DateToDi(Func):
3553class DateToDi(Func):
3554    pass
class Day(Func):
3557class Day(Func):
3558    pass
class Decode(Func):
3561class Decode(Func):
3562    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3565class DiToDate(Func):
3566    pass
class Encode(Func):
3569class Encode(Func):
3570    arg_types = {"this": True, "charset": True}
class Exp(Func):
3573class Exp(Func):
3574    pass
class Explode(Func):
3577class Explode(Func):
3578    pass
class ExponentialTimeDecayedAvg(AggFunc):
3581class ExponentialTimeDecayedAvg(AggFunc):
3582    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3585class Floor(Func):
3586    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3589class Greatest(Func):
3590    arg_types = {"this": True, "expressions": False}
3591    is_var_len_args = True
class GroupConcat(Func):
3594class GroupConcat(Func):
3595    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3598class GroupUniqArray(AggFunc):
3599    arg_types = {"this": True, "size": False}
class Hex(Func):
3602class Hex(Func):
3603    pass
class Histogram(AggFunc):
3606class Histogram(AggFunc):
3607    arg_types = {"this": True, "bins": False}
class If(Func):
3610class If(Func):
3611    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3614class IfNull(Func):
3615    arg_types = {"this": True, "expression": False}
3616    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3619class Initcap(Func):
3620    pass
class JSONKeyValue(Expression):
3623class JSONKeyValue(Expression):
3624    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3627class JSONObject(Func):
3628    arg_types = {
3629        "expressions": False,
3630        "null_handling": False,
3631        "unique_keys": False,
3632        "return_type": False,
3633        "format_json": False,
3634        "encoding": False,
3635    }
class JSONBContains(Binary):
3638class JSONBContains(Binary):
3639    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3642class JSONExtract(Binary, Func):
3643    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3646class JSONExtractScalar(JSONExtract):
3647    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3650class JSONBExtract(JSONExtract):
3651    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3654class JSONBExtractScalar(JSONExtract):
3655    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3658class JSONFormat(Func):
3659    arg_types = {"this": False, "options": False}
3660    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3663class Least(Func):
3664    arg_types = {"expressions": False}
3665    is_var_len_args = True
class Length(Func):
3668class Length(Func):
3669    pass
class Levenshtein(Func):
3672class Levenshtein(Func):
3673    arg_types = {
3674        "this": True,
3675        "expression": False,
3676        "ins_cost": False,
3677        "del_cost": False,
3678        "sub_cost": False,
3679    }
class Ln(Func):
3682class Ln(Func):
3683    pass
class Log(Func):
3686class Log(Func):
3687    arg_types = {"this": True, "expression": False}
class Log2(Func):
3690class Log2(Func):
3691    pass
class Log10(Func):
3694class Log10(Func):
3695    pass
class LogicalOr(AggFunc):
3698class LogicalOr(AggFunc):
3699    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3702class LogicalAnd(AggFunc):
3703    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3706class Lower(Func):
3707    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3710class Map(Func):
3711    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3714class VarMap(Func):
3715    arg_types = {"keys": True, "values": True}
3716    is_var_len_args = True
class MatchAgainst(Func):
3720class MatchAgainst(Func):
3721    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
3724class Max(AggFunc):
3725    arg_types = {"this": True, "expressions": False}
3726    is_var_len_args = True
class Min(AggFunc):
3729class Min(AggFunc):
3730    arg_types = {"this": True, "expressions": False}
3731    is_var_len_args = True
class Month(Func):
3734class Month(Func):
3735    pass
class Nvl2(Func):
3738class Nvl2(Func):
3739    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3742class Posexplode(Func):
3743    pass
class Pow(Binary, Func):
3746class Pow(Binary, Func):
3747    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3750class PercentileCont(AggFunc):
3751    pass
class PercentileDisc(AggFunc):
3754class PercentileDisc(AggFunc):
3755    pass
class Quantile(AggFunc):
3758class Quantile(AggFunc):
3759    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3764class Quantiles(AggFunc):
3765    arg_types = {"parameters": True, "expressions": True}
3766    is_var_len_args = True
class QuantileIf(AggFunc):
3769class QuantileIf(AggFunc):
3770    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3773class ApproxQuantile(Quantile):
3774    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3777class RangeN(Func):
3778    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3781class ReadCSV(Func):
3782    _sql_names = ["READ_CSV"]
3783    is_var_len_args = True
3784    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3787class Reduce(Func):
3788    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3791class RegexpExtract(Func):
3792    arg_types = {
3793        "this": True,
3794        "expression": True,
3795        "position": False,
3796        "occurrence": False,
3797        "group": False,
3798    }
class RegexpLike(Func):
3801class RegexpLike(Func):
3802    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3805class RegexpILike(Func):
3806    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3811class RegexpSplit(Func):
3812    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
3815class Repeat(Func):
3816    arg_types = {"this": True, "times": True}
class Round(Func):
3819class Round(Func):
3820    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3823class RowNumber(Func):
3824    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3827class SafeDivide(Func):
3828    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3831class SetAgg(AggFunc):
3832    pass
class SortArray(Func):
3835class SortArray(Func):
3836    arg_types = {"this": True, "asc": False}
class Split(Func):
3839class Split(Func):
3840    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3845class Substring(Func):
3846    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3849class StrPosition(Func):
3850    arg_types = {
3851        "this": True,
3852        "substr": True,
3853        "position": False,
3854        "instance": False,
3855    }
class StrToDate(Func):
3858class StrToDate(Func):
3859    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3862class StrToTime(Func):
3863    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3868class StrToUnix(Func):
3869    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3872class NumberToStr(Func):
3873    arg_types = {"this": True, "format": True}
class Struct(Func):
3876class Struct(Func):
3877    arg_types = {"expressions": True}
3878    is_var_len_args = True
class StructExtract(Func):
3881class StructExtract(Func):
3882    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3885class Sum(AggFunc):
3886    pass
class Sqrt(Func):
3889class Sqrt(Func):
3890    pass
class Stddev(AggFunc):
3893class Stddev(AggFunc):
3894    pass
class StddevPop(AggFunc):
3897class StddevPop(AggFunc):
3898    pass
class StddevSamp(AggFunc):
3901class StddevSamp(AggFunc):
3902    pass
class TimeToStr(Func):
3905class TimeToStr(Func):
3906    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3909class TimeToTimeStr(Func):
3910    pass
class TimeToUnix(Func):
3913class TimeToUnix(Func):
3914    pass
class TimeStrToDate(Func):
3917class TimeStrToDate(Func):
3918    pass
class TimeStrToTime(Func):
3921class TimeStrToTime(Func):
3922    pass
class TimeStrToUnix(Func):
3925class TimeStrToUnix(Func):
3926    pass
class Trim(Func):
3929class Trim(Func):
3930    arg_types = {
3931        "this": True,
3932        "expression": False,
3933        "position": False,
3934        "collation": False,
3935    }
class TsOrDsAdd(Func, TimeUnit):
3938class TsOrDsAdd(Func, TimeUnit):
3939    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3942class TsOrDsToDateStr(Func):
3943    pass
class TsOrDsToDate(Func):
3946class TsOrDsToDate(Func):
3947    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3950class TsOrDiToDi(Func):
3951    pass
class Unhex(Func):
3954class Unhex(Func):
3955    pass
class UnixToStr(Func):
3958class UnixToStr(Func):
3959    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3964class UnixToTime(Func):
3965    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3966
3967    SECONDS = Literal.string("seconds")
3968    MILLIS = Literal.string("millis")
3969    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3972class UnixToTimeStr(Func):
3973    pass
class Upper(Func):
3976class Upper(Func):
3977    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3980class Variance(AggFunc):
3981    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3984class VariancePop(AggFunc):
3985    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
3988class Week(Func):
3989    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
3992class XMLTable(Func):
3993    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
3996class Year(Func):
3997    pass
class Use(Expression):
4000class Use(Expression):
4001    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4004class Merge(Expression):
4005    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4008class When(Func):
4009    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4020def maybe_parse(
4021    sql_or_expression: ExpOrStr,
4022    *,
4023    into: t.Optional[IntoType] = None,
4024    dialect: DialectType = None,
4025    prefix: t.Optional[str] = None,
4026    copy: bool = False,
4027    **opts,
4028) -> Expression:
4029    """Gracefully handle a possible string or expression.
4030
4031    Example:
4032        >>> maybe_parse("1")
4033        (LITERAL this: 1, is_string: False)
4034        >>> maybe_parse(to_identifier("x"))
4035        (IDENTIFIER this: x, quoted: False)
4036
4037    Args:
4038        sql_or_expression: the SQL code string or an expression
4039        into: the SQLGlot Expression to parse into
4040        dialect: the dialect used to parse the input expressions (in the case that an
4041            input expression is a SQL string).
4042        prefix: a string to prefix the sql with before it gets parsed
4043            (automatically includes a space)
4044        copy: whether or not to copy the expression.
4045        **opts: other options to use to parse the input expressions (again, in the case
4046            that an input expression is a SQL string).
4047
4048    Returns:
4049        Expression: the parsed or given expression.
4050    """
4051    if isinstance(sql_or_expression, Expression):
4052        if copy:
4053            return sql_or_expression.copy()
4054        return sql_or_expression
4055
4056    import sqlglot
4057
4058    sql = str(sql_or_expression)
4059    if prefix:
4060        sql = f"{prefix} {sql}"
4061    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4207def union(left, right, distinct=True, dialect=None, **opts):
4208    """
4209    Initializes a syntax tree from one UNION expression.
4210
4211    Example:
4212        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4213        'SELECT * FROM foo UNION SELECT * FROM bla'
4214
4215    Args:
4216        left (str | Expression): the SQL code string corresponding to the left-hand side.
4217            If an `Expression` instance is passed, it will be used as-is.
4218        right (str | Expression): the SQL code string corresponding to the right-hand side.
4219            If an `Expression` instance is passed, it will be used as-is.
4220        distinct (bool): set the DISTINCT flag if and only if this is true.
4221        dialect (str): the dialect used to parse the input expression.
4222        opts (kwargs): other options to use to parse the input expressions.
4223    Returns:
4224        Union: the syntax tree for the UNION expression.
4225    """
4226    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4227    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4228
4229    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4232def intersect(left, right, distinct=True, dialect=None, **opts):
4233    """
4234    Initializes a syntax tree from one INTERSECT expression.
4235
4236    Example:
4237        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4238        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4239
4240    Args:
4241        left (str | Expression): the SQL code string corresponding to the left-hand side.
4242            If an `Expression` instance is passed, it will be used as-is.
4243        right (str | Expression): the SQL code string corresponding to the right-hand side.
4244            If an `Expression` instance is passed, it will be used as-is.
4245        distinct (bool): set the DISTINCT flag if and only if this is true.
4246        dialect (str): the dialect used to parse the input expression.
4247        opts (kwargs): other options to use to parse the input expressions.
4248    Returns:
4249        Intersect: the syntax tree for the INTERSECT expression.
4250    """
4251    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4252    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4253
4254    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4257def except_(left, right, distinct=True, dialect=None, **opts):
4258    """
4259    Initializes a syntax tree from one EXCEPT expression.
4260
4261    Example:
4262        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4263        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4264
4265    Args:
4266        left (str | Expression): the SQL code string corresponding to the left-hand side.
4267            If an `Expression` instance is passed, it will be used as-is.
4268        right (str | Expression): the SQL code string corresponding to the right-hand side.
4269            If an `Expression` instance is passed, it will be used as-is.
4270        distinct (bool): set the DISTINCT flag if and only if this is true.
4271        dialect (str): the dialect used to parse the input expression.
4272        opts (kwargs): other options to use to parse the input expressions.
4273    Returns:
4274        Except: the syntax tree for the EXCEPT statement.
4275    """
4276    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4277    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4278
4279    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4282def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4283    """
4284    Initializes a syntax tree from one or multiple SELECT expressions.
4285
4286    Example:
4287        >>> select("col1", "col2").from_("tbl").sql()
4288        'SELECT col1, col2 FROM tbl'
4289
4290    Args:
4291        *expressions: the SQL code string to parse as the expressions of a
4292            SELECT statement. If an Expression instance is passed, this is used as-is.
4293        dialect: the dialect used to parse the input expressions (in the case that an
4294            input expression is a SQL string).
4295        **opts: other options to use to parse the input expressions (again, in the case
4296            that an input expression is a SQL string).
4297
4298    Returns:
4299        Select: the syntax tree for the SELECT statement.
4300    """
4301    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4304def from_(*expressions, dialect=None, **opts) -> Select:
4305    """
4306    Initializes a syntax tree from a FROM expression.
4307
4308    Example:
4309        >>> from_("tbl").select("col1", "col2").sql()
4310        'SELECT col1, col2 FROM tbl'
4311
4312    Args:
4313        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4314            SELECT statement. If an Expression instance is passed, this is used as-is.
4315        dialect (str): the dialect used to parse the input expression (in the case that the
4316            input expression is a SQL string).
4317        **opts: other options to use to parse the input expressions (again, in the case
4318            that the input expression is a SQL string).
4319
4320    Returns:
4321        Select: the syntax tree for the SELECT statement.
4322    """
4323    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4326def update(
4327    table: str | Table,
4328    properties: dict,
4329    where: t.Optional[ExpOrStr] = None,
4330    from_: t.Optional[ExpOrStr] = None,
4331    dialect: DialectType = None,
4332    **opts,
4333) -> Update:
4334    """
4335    Creates an update statement.
4336
4337    Example:
4338        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4339        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4340
4341    Args:
4342        *properties: dictionary of properties to set which are
4343            auto converted to sql objects eg None -> NULL
4344        where: sql conditional parsed into a WHERE statement
4345        from_: sql statement parsed into a FROM statement
4346        dialect: the dialect used to parse the input expressions.
4347        **opts: other options to use to parse the input expressions.
4348
4349    Returns:
4350        Update: the syntax tree for the UPDATE statement.
4351    """
4352    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4353    update_expr.set(
4354        "expressions",
4355        [
4356            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4357            for k, v in properties.items()
4358        ],
4359    )
4360    if from_:
4361        update_expr.set(
4362            "from",
4363            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4364        )
4365    if isinstance(where, Condition):
4366        where = Where(this=where)
4367    if where:
4368        update_expr.set(
4369            "where",
4370            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4371        )
4372    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4375def delete(
4376    table: ExpOrStr,
4377    where: t.Optional[ExpOrStr] = None,
4378    returning: t.Optional[ExpOrStr] = None,
4379    dialect: DialectType = None,
4380    **opts,
4381) -> Delete:
4382    """
4383    Builds a delete statement.
4384
4385    Example:
4386        >>> delete("my_table", where="id > 1").sql()
4387        'DELETE FROM my_table WHERE id > 1'
4388
4389    Args:
4390        where: sql conditional parsed into a WHERE statement
4391        returning: sql conditional parsed into a RETURNING statement
4392        dialect: the dialect used to parse the input expressions.
4393        **opts: other options to use to parse the input expressions.
4394
4395    Returns:
4396        Delete: the syntax tree for the DELETE statement.
4397    """
4398    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4399    if where:
4400        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4401    if returning:
4402        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4403    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4406def condition(expression, dialect=None, **opts) -> Condition:
4407    """
4408    Initialize a logical condition expression.
4409
4410    Example:
4411        >>> condition("x=1").sql()
4412        'x = 1'
4413
4414        This is helpful for composing larger logical syntax trees:
4415        >>> where = condition("x=1")
4416        >>> where = where.and_("y=1")
4417        >>> Select().from_("tbl").select("*").where(where).sql()
4418        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4419
4420    Args:
4421        *expression (str | Expression): the SQL code string to parse.
4422            If an Expression instance is passed, this is used as-is.
4423        dialect (str): the dialect used to parse the input expression (in the case that the
4424            input expression is a SQL string).
4425        **opts: other options to use to parse the input expressions (again, in the case
4426            that the input expression is a SQL string).
4427
4428    Returns:
4429        Condition: the expression
4430    """
4431    return maybe_parse(  # type: ignore
4432        expression,
4433        into=Condition,
4434        dialect=dialect,
4435        **opts,
4436    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4439def and_(*expressions, dialect=None, **opts) -> And:
4440    """
4441    Combine multiple conditions with an AND logical operator.
4442
4443    Example:
4444        >>> and_("x=1", and_("y=1", "z=1")).sql()
4445        'x = 1 AND (y = 1 AND z = 1)'
4446
4447    Args:
4448        *expressions (str | Expression): the SQL code strings to parse.
4449            If an Expression instance is passed, this is used as-is.
4450        dialect (str): the dialect used to parse the input expression.
4451        **opts: other options to use to parse the input expressions.
4452
4453    Returns:
4454        And: the new condition
4455    """
4456    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4459def or_(*expressions, dialect=None, **opts) -> Or:
4460    """
4461    Combine multiple conditions with an OR logical operator.
4462
4463    Example:
4464        >>> or_("x=1", or_("y=1", "z=1")).sql()
4465        'x = 1 OR (y = 1 OR z = 1)'
4466
4467    Args:
4468        *expressions (str | Expression): the SQL code strings to parse.
4469            If an Expression instance is passed, this is used as-is.
4470        dialect (str): the dialect used to parse the input expression.
4471        **opts: other options to use to parse the input expressions.
4472
4473    Returns:
4474        Or: the new condition
4475    """
4476    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4479def not_(expression, dialect=None, **opts) -> Not:
4480    """
4481    Wrap a condition with a NOT operator.
4482
4483    Example:
4484        >>> not_("this_suit='black'").sql()
4485        "NOT this_suit = 'black'"
4486
4487    Args:
4488        expression (str | Expression): the SQL code strings to parse.
4489            If an Expression instance is passed, this is used as-is.
4490        dialect (str): the dialect used to parse the input expression.
4491        **opts: other options to use to parse the input expressions.
4492
4493    Returns:
4494        Not: the new condition
4495    """
4496    this = condition(
4497        expression,
4498        dialect=dialect,
4499        **opts,
4500    )
4501    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4504def paren(expression) -> Paren:
4505    return Paren(this=expression)
def to_identifier(name, quoted=None):
4521def to_identifier(name, quoted=None):
4522    """Builds an identifier.
4523
4524    Args:
4525        name: The name to turn into an identifier.
4526        quoted: Whether or not force quote the identifier.
4527
4528    Returns:
4529        The identifier ast node.
4530    """
4531
4532    if name is None:
4533        return None
4534
4535    if isinstance(name, Identifier):
4536        identifier = name
4537    elif isinstance(name, str):
4538        identifier = Identifier(
4539            this=name,
4540            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4541        )
4542    else:
4543        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4544    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4550def to_interval(interval: str | Literal) -> Interval:
4551    """Builds an interval expression from a string like '1 day' or '5 months'."""
4552    if isinstance(interval, Literal):
4553        if not interval.is_string:
4554            raise ValueError("Invalid interval string.")
4555
4556        interval = interval.this
4557
4558    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4559
4560    if not interval_parts:
4561        raise ValueError("Invalid interval string.")
4562
4563    return Interval(
4564        this=Literal.string(interval_parts.group(1)),
4565        unit=Var(this=interval_parts.group(2)),
4566    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4579def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4580    """
4581    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4582    If a table is passed in then that table is returned.
4583
4584    Args:
4585        sql_path: a `[catalog].[schema].[table]` string.
4586
4587    Returns:
4588        A table expression.
4589    """
4590    if sql_path is None or isinstance(sql_path, Table):
4591        return sql_path
4592    if not isinstance(sql_path, str):
4593        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4594
4595    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4596    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4599def to_column(sql_path: str | Column, **kwargs) -> Column:
4600    """
4601    Create a column from a `[table].[column]` sql path. Schema is optional.
4602
4603    If a column is passed in then that column is returned.
4604
4605    Args:
4606        sql_path: `[table].[column]` string
4607    Returns:
4608        Table: A column expression
4609    """
4610    if sql_path is None or isinstance(sql_path, Column):
4611        return sql_path
4612    if not isinstance(sql_path, str):
4613        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4614    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4617def alias_(
4618    expression: ExpOrStr,
4619    alias: str | Identifier,
4620    table: bool | t.Sequence[str | Identifier] = False,
4621    quoted: t.Optional[bool] = None,
4622    dialect: DialectType = None,
4623    **opts,
4624):
4625    """Create an Alias expression.
4626
4627    Example:
4628        >>> alias_('foo', 'bar').sql()
4629        'foo AS bar'
4630
4631        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4632        '(SELECT 1, 2) AS bar(a, b)'
4633
4634    Args:
4635        expression: the SQL code strings to parse.
4636            If an Expression instance is passed, this is used as-is.
4637        alias: the alias name to use. If the name has
4638            special characters it is quoted.
4639        table: Whether or not to create a table alias, can also be a list of columns.
4640        quoted: whether or not to quote the alias
4641        dialect: the dialect used to parse the input expression.
4642        **opts: other options to use to parse the input expressions.
4643
4644    Returns:
4645        Alias: the aliased expression
4646    """
4647    exp = maybe_parse(expression, dialect=dialect, **opts)
4648    alias = to_identifier(alias, quoted=quoted)
4649
4650    if table:
4651        table_alias = TableAlias(this=alias)
4652        exp.set("alias", table_alias)
4653
4654        if not isinstance(table, bool):
4655            for column in table:
4656                table_alias.append("columns", to_identifier(column, quoted=quoted))
4657
4658        return exp
4659
4660    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4661    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4662    # for the complete Window expression.
4663    #
4664    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4665
4666    if "alias" in exp.arg_types and not isinstance(exp, Window):
4667        exp = exp.copy()
4668        exp.set("alias", alias)
4669        return exp
4670    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4673def subquery(expression, alias=None, dialect=None, **opts):
4674    """
4675    Build a subquery expression.
4676
4677    Example:
4678        >>> subquery('select x from tbl', 'bar').select('x').sql()
4679        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4680
4681    Args:
4682        expression (str | Expression): the SQL code strings to parse.
4683            If an Expression instance is passed, this is used as-is.
4684        alias (str | Expression): the alias name to use.
4685        dialect (str): the dialect used to parse the input expression.
4686        **opts: other options to use to parse the input expressions.
4687
4688    Returns:
4689        Select: a new select with the subquery expression included
4690    """
4691
4692    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4693    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4696def column(
4697    col: str | Identifier,
4698    table: t.Optional[str | Identifier] = None,
4699    db: t.Optional[str | Identifier] = None,
4700    catalog: t.Optional[str | Identifier] = None,
4701    quoted: t.Optional[bool] = None,
4702) -> Column:
4703    """
4704    Build a Column.
4705
4706    Args:
4707        col: column name
4708        table: table name
4709        db: db name
4710        catalog: catalog name
4711        quoted: whether or not to force quote each part
4712    Returns:
4713        Column: column instance
4714    """
4715    return Column(
4716        this=to_identifier(col, quoted=quoted),
4717        table=to_identifier(table, quoted=quoted),
4718        db=to_identifier(db, quoted=quoted),
4719        catalog=to_identifier(catalog, quoted=quoted),
4720    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4723def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4724    """Cast an expression to a data type.
4725
4726    Example:
4727        >>> cast('x + 1', 'int').sql()
4728        'CAST(x + 1 AS INT)'
4729
4730    Args:
4731        expression: The expression to cast.
4732        to: The datatype to cast to.
4733
4734    Returns:
4735        A cast node.
4736    """
4737    expression = maybe_parse(expression, **opts)
4738    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4741def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4742    """Build a Table.
4743
4744    Args:
4745        table (str | Expression): column name
4746        db (str | Expression): db name
4747        catalog (str | Expression): catalog name
4748
4749    Returns:
4750        Table: table instance
4751    """
4752    return Table(
4753        this=to_identifier(table, quoted=quoted),
4754        db=to_identifier(db, quoted=quoted),
4755        catalog=to_identifier(catalog, quoted=quoted),
4756        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4757    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4760def values(
4761    values: t.Iterable[t.Tuple[t.Any, ...]],
4762    alias: t.Optional[str] = None,
4763    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4764) -> Values:
4765    """Build VALUES statement.
4766
4767    Example:
4768        >>> values([(1, '2')]).sql()
4769        "VALUES (1, '2')"
4770
4771    Args:
4772        values: values statements that will be converted to SQL
4773        alias: optional alias
4774        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4775         If either are provided then an alias is also required.
4776         If a dictionary is provided then the first column of the values will be casted to the expected type
4777         in order to help with type inference.
4778
4779    Returns:
4780        Values: the Values expression object
4781    """
4782    if columns and not alias:
4783        raise ValueError("Alias is required when providing columns")
4784    table_alias = (
4785        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4786        if columns
4787        else TableAlias(this=to_identifier(alias) if alias else None)
4788    )
4789    expressions = [convert(tup) for tup in values]
4790    if columns and isinstance(columns, dict):
4791        types = list(columns.values())
4792        expressions[0].set(
4793            "expressions",
4794            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4795        )
4796    return Values(
4797        expressions=expressions,
4798        alias=table_alias,
4799    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4802def var(name: t.Optional[ExpOrStr]) -> Var:
4803    """Build a SQL variable.
4804
4805    Example:
4806        >>> repr(var('x'))
4807        '(VAR this: x)'
4808
4809        >>> repr(var(column('x', table='y')))
4810        '(VAR this: x)'
4811
4812    Args:
4813        name: The name of the var or an expression who's name will become the var.
4814
4815    Returns:
4816        The new variable node.
4817    """
4818    if not name:
4819        raise ValueError("Cannot convert empty name into var.")
4820
4821    if isinstance(name, Expression):
4822        name = name.name
4823    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
4826def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4827    """Build ALTER TABLE... RENAME... expression
4828
4829    Args:
4830        old_name: The old name of the table
4831        new_name: The new name of the table
4832
4833    Returns:
4834        Alter table expression
4835    """
4836    old_table = to_table(old_name)
4837    new_table = to_table(new_name)
4838    return AlterTable(
4839        this=old_table,
4840        actions=[
4841            RenameTable(this=new_table),
4842        ],
4843    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value) -> sqlglot.expressions.Expression:
4846def convert(value) -> Expression:
4847    """Convert a python value into an expression object.
4848
4849    Raises an error if a conversion is not possible.
4850
4851    Args:
4852        value (Any): a python object
4853
4854    Returns:
4855        Expression: the equivalent expression object
4856    """
4857    if isinstance(value, Expression):
4858        return value
4859    if value is None:
4860        return NULL
4861    if isinstance(value, bool):
4862        return Boolean(this=value)
4863    if isinstance(value, str):
4864        return Literal.string(value)
4865    if isinstance(value, float) and math.isnan(value):
4866        return NULL
4867    if isinstance(value, numbers.Number):
4868        return Literal.number(value)
4869    if isinstance(value, tuple):
4870        return Tuple(expressions=[convert(v) for v in value])
4871    if isinstance(value, list):
4872        return Array(expressions=[convert(v) for v in value])
4873    if isinstance(value, dict):
4874        return Map(
4875            keys=[convert(k) for k in value],
4876            values=[convert(v) for v in value.values()],
4877        )
4878    if isinstance(value, datetime.datetime):
4879        datetime_literal = Literal.string(
4880            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4881        )
4882        return TimeStrToTime(this=datetime_literal)
4883    if isinstance(value, datetime.date):
4884        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4885        return DateStrToDate(this=date_literal)
4886    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4889def replace_children(expression, fun, *args, **kwargs):
4890    """
4891    Replace children of an expression with the result of a lambda fun(child) -> exp.
4892    """
4893    for k, v in expression.args.items():
4894        is_list_arg = type(v) is list
4895
4896        child_nodes = v if is_list_arg else [v]
4897        new_child_nodes = []
4898
4899        for cn in child_nodes:
4900            if isinstance(cn, Expression):
4901                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4902                    new_child_nodes.append(child_node)
4903                    child_node.parent = expression
4904                    child_node.arg_key = k
4905            else:
4906                new_child_nodes.append(cn)
4907
4908        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
4911def column_table_names(expression):
4912    """
4913    Return all table names referenced through columns in an expression.
4914
4915    Example:
4916        >>> import sqlglot
4917        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4918        ['c', 'a']
4919
4920    Args:
4921        expression (sqlglot.Expression): expression to find table names
4922
4923    Returns:
4924        list: A list of unique names
4925    """
4926    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
4929def table_name(table) -> str:
4930    """Get the full name of a table as a string.
4931
4932    Args:
4933        table (exp.Table | str): table expression node or string.
4934
4935    Examples:
4936        >>> from sqlglot import exp, parse_one
4937        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4938        'a.b.c'
4939
4940    Returns:
4941        The table name.
4942    """
4943
4944    table = maybe_parse(table, into=Table)
4945
4946    if not table:
4947        raise ValueError(f"Cannot parse {table}")
4948
4949    return ".".join(
4950        part
4951        for part in (
4952            table.text("catalog"),
4953            table.text("db"),
4954            table.name,
4955        )
4956        if part
4957    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
4960def replace_tables(expression, mapping):
4961    """Replace all tables in expression according to the mapping.
4962
4963    Args:
4964        expression (sqlglot.Expression): expression node to be transformed and replaced.
4965        mapping (Dict[str, str]): mapping of table names.
4966
4967    Examples:
4968        >>> from sqlglot import exp, parse_one
4969        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4970        'SELECT * FROM c'
4971
4972    Returns:
4973        The mapped expression.
4974    """
4975
4976    def _replace_tables(node):
4977        if isinstance(node, Table):
4978            new_name = mapping.get(table_name(node))
4979            if new_name:
4980                return to_table(
4981                    new_name,
4982                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4983                )
4984        return node
4985
4986    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
4989def replace_placeholders(expression, *args, **kwargs):
4990    """Replace placeholders in an expression.
4991
4992    Args:
4993        expression (sqlglot.Expression): expression node to be transformed and replaced.
4994        args: positional names that will substitute unnamed placeholders in the given order.
4995        kwargs: keyword arguments that will substitute named placeholders.
4996
4997    Examples:
4998        >>> from sqlglot import exp, parse_one
4999        >>> replace_placeholders(
5000        ...     parse_one("select * from :tbl where ? = ?"),
5001        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5002        ... ).sql()
5003        "SELECT * FROM foo WHERE str_col = 'b'"
5004
5005    Returns:
5006        The mapped expression.
5007    """
5008
5009    def _replace_placeholders(node, args, **kwargs):
5010        if isinstance(node, Placeholder):
5011            if node.name:
5012                new_name = kwargs.get(node.name)
5013                if new_name:
5014                    return convert(new_name)
5015            else:
5016                try:
5017                    return convert(next(args))
5018                except StopIteration:
5019                    pass
5020        return node
5021
5022    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
5025def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5026    """Transforms an expression by expanding all referenced sources into subqueries.
5027
5028    Examples:
5029        >>> from sqlglot import parse_one
5030        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5031        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5032
5033    Args:
5034        expression: The expression to expand.
5035        sources: A dictionary of name to Subqueryables.
5036        copy: Whether or not to copy the expression during transformation. Defaults to True.
5037
5038    Returns:
5039        The transformed expression.
5040    """
5041
5042    def _expand(node: Expression):
5043        if isinstance(node, Table):
5044            name = table_name(node)
5045            source = sources.get(name)
5046            if source:
5047                subquery = source.subquery(node.alias or name)
5048                subquery.comments = [f"source: {name}"]
5049                return subquery
5050        return node
5051
5052    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5055def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5056    """
5057    Returns a Func expression.
5058
5059    Examples:
5060        >>> func("abs", 5).sql()
5061        'ABS(5)'
5062
5063        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5064        'CAST(5 AS DOUBLE)'
5065
5066    Args:
5067        name: the name of the function to build.
5068        args: the args used to instantiate the function of interest.
5069        dialect: the source dialect.
5070        kwargs: the kwargs used to instantiate the function of interest.
5071
5072    Note:
5073        The arguments `args` and `kwargs` are mutually exclusive.
5074
5075    Returns:
5076        An instance of the function of interest, or an anonymous function, if `name` doesn't
5077        correspond to an existing `sqlglot.expressions.Func` class.
5078    """
5079    if args and kwargs:
5080        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5081
5082    from sqlglot.dialects.dialect import Dialect
5083
5084    converted = [convert(arg) for arg in args]
5085    kwargs = {key: convert(value) for key, value in kwargs.items()}
5086
5087    parser = Dialect.get_or_raise(dialect)().parser()
5088    from_args_list = parser.FUNCTIONS.get(name.upper())
5089
5090    if from_args_list:
5091        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5092    else:
5093        kwargs = kwargs or {"expressions": converted}
5094        function = Anonymous(this=name, **kwargs)
5095
5096    for error_message in function.error_messages(converted):
5097        raise ValueError(error_message)
5098
5099    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5102def true():
5103    """
5104    Returns a true Boolean expression.
5105    """
5106    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5109def false():
5110    """
5111    Returns a false Boolean expression.
5112    """
5113    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5116def null():
5117    """
5118    Returns a Null expression.
5119    """
5120    return Null()

Returns a Null expression.